Beispiel #1
0
def _create_output_layout():
    """
    Tab layout for output parameters, populated from properties_metadata.json
    """
    app = widgets.Tab()
    children = []

    with open("properties_metadata.json") as f:
        data = json.load(f)

    for i, title in enumerate(data):
        grid_layout = widgets.GridspecLayout(10, 2, width="100%")
        for j, prop in enumerate(data[title]):
            fn = _FunctionInfo(prop["module_name"], prop["function_name"])
            if "spec_combo" in prop:
                for spec_combo in prop["spec_combo"]:
                    fn.add_combo(spec_combo)
            grid_layout[j, 0] = _create_label(prop["function_name"] + ":")
            grid_layout[j, 1] = fn.get_output_widget()
            _process_queue.append(fn)
        children.append(grid_layout)
        app.set_title(i, title)
    app.children = children

    return app
Beispiel #2
0
def show_decomposition_series(node, **kwargs):
    # Use Rendering... as a placeholder
    ntabs = 2
    children = [widgets.HTML("Rendering...") for _ in range(ntabs)]

    def on_selected_index(change):
        # Click on Traces Tab
        if change.new == 1 and isinstance(change.owner.children[1], widgets.HTML):
            widget_box = show_decomposition_traces(node)
            children[1] = widget_box
            change.owner.children = children

    field_lay = widgets.Layout(
        max_height="40px", max_width="500px", min_height="30px", min_width="130px"
    )
    vbox = []
    for key, val in node.fields.items():
        lbl_key = widgets.Label(key + ":", layout=field_lay)
        lbl_val = widgets.Label(str(val), layout=field_lay)
        vbox.append(widgets.HBox(children=[lbl_key, lbl_val]))
    children[0] = widgets.VBox(vbox)

    tab_nest = widgets.Tab()
    tab_nest.children = children
    tab_nest.set_title(0, "Fields")
    tab_nest.set_title(1, "Traces")
    tab_nest.observe(on_selected_index, names="selected_index")
    return tab_nest
Beispiel #3
0
def interactive_explore(ls):
    """Create a widget to visually explore a dataset summary.

    Note that the widget will only work when created within a Jupyter notebook.

    Parameters
    ----------
    ls : :class:`~lens.Summary`
        Lens `Summary`.

    Returns
    -------
    :class:`ipywidgets.Widget`
        Jupyter widget with summary plots.
    """
    if not IN_NOTEBOOK:
        message = ("Lens interactive_explore can only be used in a"
                   " Jupyter notebook")
        logger.error(message)
        raise ValueError(message)

    tabs = widgets.Tab()
    tabs.children = [
        create_distribution_plot_widget(ls),
        create_cdf_plot_widget(ls),
        create_pairdensity_plot_widget(ls),
        create_correlation_plot_widget(ls),
    ]

    tabs.set_title(0, "Distribution")
    tabs.set_title(1, "CDF")
    tabs.set_title(2, "Pairwise density")
    tabs.set_title(3, "Correlation matrix")

    return tabs
Beispiel #4
0
def i_show_logs(job_prefix):
    """
    """
    from ipywidgets import widgets, Layout
    from IPython.display import display, clear_output
    from os.path import isfile
    outfile = f'{job_prefix}.output'
    errfile = f'{job_prefix}.error'
    logfile = f'{job_prefix}.cobaltlog'
    if (isfile(outfile)):
        with open(outfile, 'r') as f:
            out = f.read()
        with open(errfile, 'r') as f:
            err = f.read()
        with open(logfile, 'r') as f:
            log = f.read()
        children = [
            widgets.Textarea(value=val,
                             layout=Layout(flex='1 1 auto',
                                           width='100%',
                                           height='400px'))
            for name, val in [(outfile, out), (errfile, err), (logfile, log)]
        ]
        tab = widgets.Tab(children=children,
                          layout=Layout(flex='1 1 auto',
                                        width='100%',
                                        height='auto'))
        #ow = widgets.Textarea(value=out,description=outfile)
        #ew = widgets.Textarea(value=err,description=errfile)
        #lw = widgets.Textarea(value=log,description=logfile)
        tab.set_title(0, outfile)
        tab.set_title(1, errfile)
        tab.set_title(2, logfile)
        display(tab)
    return
Beispiel #5
0
def show_decomposition_series(node, **kwargs):
    # Use Rendering... as a placeholder
    ntabs = 2
    children = [widgets.HTML('Rendering...') for _ in range(ntabs)]

    def on_selected_index(change):
        # Click on Traces Tab
        if change.new == 1 and isinstance(change.owner.children[1],
                                          widgets.HTML):
            widget_box = show_decomposition_traces(node)
            children[1] = widget_box
            change.owner.children = children

    field_lay = widgets.Layout(max_height='40px',
                               max_width='500px',
                               min_height='30px',
                               min_width='130px')
    vbox = []
    for key, val in node.fields.items():
        lbl_key = widgets.Label(key + ':', layout=field_lay)
        lbl_val = widgets.Label(str(val), layout=field_lay)
        vbox.append(widgets.HBox(children=[lbl_key, lbl_val]))
        #vbox.append(widgets.Text(value=repr(value), description=key, disabled=True))
    children[0] = widgets.VBox(vbox)

    tab_nest = widgets.Tab()
    tab_nest.children = children
    tab_nest.set_title(0, 'Fields')
    tab_nest.set_title(1, 'Traces')
    tab_nest.observe(on_selected_index, names='selected_index')
    return tab_nest
Beispiel #6
0
def building_pm_view(project_name, platform='jupyter'):
    assert platform == 'jupyter' or platform == 'flask'
    '''project_level_table_view = build_table_widget(
      current_level = 'project',
      with_subtable = True,
      next_level = 'member')'''
    member_level_table_view = build_top_table_widget(current_level='member',
                                                     with_subtable=True,
                                                     next_level='table',
                                                     condition=project_name,
                                                     condition_type='project')

    table_view = build_top_table_widget(current_level='table',
                                        with_subtable=False,
                                        condition=project_name,
                                        condition_type='project')

    tab_nest = widgets.Tab()
    tab_nest.children = [member_level_table_view, table_view]
    tab_nest.set_title(0, 'member-level information')
    tab_nest.set_title(1, 'table-level information')
    if platform == 'flask':
        embed_minimal_html(project_name + '.html',
                           views=[tab_nest],
                           title=project_name)
        return open(project_name + '.html').read()
    else:  # platform == jupyter
        return VBox([Label(value="Project: " + project_name), tab_nest])
Beispiel #7
0
    def render(self, change=None):
        header = widgets.HTML(
            header_template.render(name=self.exp.task,
                                   status=self.status,
                                   app_id=self.exp.app_id))

        tabs = widgets.Tab(children=[self.config_tab])
        tabs.set_title(0, "Configuration")
        self.children = [header, tabs]
Beispiel #8
0
    def print_result(self):

        timestamp_text_area = ["File name -> Time stamp (s)\n"]
        for _index, _file in enumerate(self.list_files):
            _short_file = os.path.basename(_file)
            _time = self.list_time_stamp[_index]
            _text = "{} -> {}".format(_short_file, _time)
            timestamp_text_area.append(_text)
        timestamp_text_area = "\n".join(timestamp_text_area)

        relative_text_area = [
            "file name -> (current image acquistion time - previous image acquisition time) \n"
        ]
        for _index, _file in enumerate(self.list_files):
            _short_file = os.path.basename(_file)
            _relative_time = self.relative_time_offset[_index]
            _text = "{} -> {}".format(_short_file, _relative_time)
            relative_text_area.append(_text)
        relative_text_area = "\n".join(relative_text_area)

        absolute_text_area = [
            "file name -> (current image acquistion time - first image acquisition time) \n"
        ]
        for _index, _file in enumerate(self.list_files):
            _short_file = os.path.basename(_file)
            _absolute_time = self.absolute_time_offset[_index]
            _text = "{} -> {}".format(_short_file, _absolute_time)
            absolute_text_area.append(_text)
        absolute_text_area = "\n".join(absolute_text_area)

        children = [
            widgets.Textarea("",
                             layout=widgets.Layout(width="100%",
                                                   height="300px")),
            widgets.Textarea("",
                             layout=widgets.Layout(width="100%",
                                                   height="300px")),
            widgets.Textarea("",
                             layout=widgets.Layout(width="100%",
                                                   height="300px"))
        ]
        tab = widgets.Tab()
        tab.children = children
        tab.set_title(0, "Time Stamp(s)")
        tab.set_title(1, "Relative (s)")
        tab.set_title(2, "Absolute (s)")

        timestamp_text = children[0]
        timestamp_text.value = timestamp_text_area

        relative_text = children[1]
        relative_text.value = relative_text_area
        absolute_text = children[2]
        absolute_text.value = absolute_text_area

        display(tab)
Beispiel #9
0
 def make_tabs(self):
     tab = widgets.Tab(children=[
         self.make_sources_tab(),
         self.make_sink_tab(),
         self.make_parameters_tab()
     ])
     tab_titles = ["Sources", "Sink", "Parameters"]
     for i in range(len(tab_titles)):
         tab.set_title(i, tab_titles[i])
     return tab
def dashboard(plotting):
    """
    Entry point to display complete Dashboard.

    :param plotting: Plotting implementation to use.
    :return:
    """
    tabs = widgets.Tab()
    container = Container(tabs, plotting)
    nav = navbar(plotting.agg.study, container)
    return widgets.VBox([nav, tabs])
def get_tabs(items: List[Renderable]) -> widgets.Tab:
    children = []
    titles = []
    for item in items:
        children.append(item.render())
        titles.append(get_name(item))

    tab = widgets.Tab()
    tab.children = children
    for id, title in enumerate(titles):
        tab.set_title(id, title)
    return tab
Beispiel #12
0
def show_lfp(node, **kwargs):
    lfp = node.electrical_series['lfp']
    ntabs = 3
    children = [widgets.HTML('Rendering...') for _ in range(ntabs)]

    def on_selected_index(change):
        if change.new == 1 and isinstance(change.owner.children[1], widgets.HTML):
            slider = widgets.IntSlider(value=0, min=0, max=lfp.data.shape[1] - 1, description='Channel',
                                       orientation='horizontal')

            def create_spectrogram(channel=0):
                f, t, Zxx = stft(lfp.data[:, channel], lfp.rate, nperseg=128)
                spect = np.log(np.abs(Zxx))
                image = itk.GetImageFromArray(spect)
                image.SetSpacing([(f[1] - f[0]), (t[1] - t[0]) * 1e-1])
                direction = image.GetDirection()
                vnl_matrix = direction.GetVnlMatrix()
                vnl_matrix.set(0, 0, 0.0)
                vnl_matrix.set(0, 1, -1.0)
                vnl_matrix.set(1, 0, 1.0)
                vnl_matrix.set(1, 1, 0.0)
                return image

            spectrogram = create_spectrogram(0)

            viewer = itkwidgets.view(spectrogram, ui_collapsed=True, select_roi=True, annotations=False)
            spect_vbox = widgets.VBox([slider, viewer])
            children[1] = spect_vbox
            change.owner.children = children
            channel_to_spectrogram = {0: spectrogram}

            def on_change_channel(change):
                channel = change.new
                if channel not in channel_to_spectrogram:
                    channel_to_spectrogram[channel] = create_spectrogram(channel)
                viewer.image = channel_to_spectrogram[channel]

            slider.observe(on_change_channel, names='value')

    vbox = []
    for key, value in lfp.fields.items():
        vbox.append(widgets.Text(value=repr(value), description=key, disabled=True))
    children[0] = widgets.VBox(vbox)

    tab_nest = widgets.Tab()
    # Use Rendering... as a placeholder
    tab_nest.children = children
    tab_nest.set_title(0, 'Fields')
    tab_nest.set_title(1, 'Spectrogram')
    tab_nest.set_title(2, 'test')
    tab_nest.observe(on_selected_index, names='selected_index')
    return tab_nest
Beispiel #13
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)
Beispiel #14
0
    def _create_ui(self):
        """Create and initialize widgets"""

        # ------------
        # Callbacks + logic
        # ------------
        def button_pressed(obj):
            self.query_im_index = int(obj.value)
            self.update()

        # ------------
        # UI - image grid
        # ------------
        self.w_imgs = []
        self.w_buttons = []
        w_img_buttons = []

        for i in range(self.rows * self.cols):
            # Initialize images
            w_img = widgets.Image(description="", width=180)
            self.w_imgs.append(w_img)

            # Initialize buttons
            w_button = widgets.Button(description="", value=i)
            w_button.on_click(button_pressed)
            if i == 0:
                w_button.button_style = "primary"
            else:
                w_button.button_style = "warning"
            self.w_buttons.append(w_button)

            # combine into image+button widget
            w_img_button = widgets.VBox(children=[w_button, w_img])
            w_img_buttons.append(w_img_button)

        # Image grid
        w_grid_HBoxes = []
        for r in range(self.rows):
            hbox = widgets.HBox(children=[
                w_img_buttons[r * self.cols + c] for c in range(self.cols)
            ])
            hbox.layout.padding = "10px"
            w_grid_HBoxes.append(hbox)
        w_img_grid = widgets.VBox(w_grid_HBoxes)

        # Create tab
        self.ui = widgets.Tab(children=[w_img_grid])
        self.ui.set_title(0, "Image retrieval viewer")

        # Fill UI with content
        self.update()
Beispiel #15
0
    def display(self):

        path_selection_output = widgets.Output()
        grading_output = widgets.Output()
        summary_output = widgets.Output()
        with path_selection_output:  # info
            print('System Overview')
            self.dashboard_path()
        with grading_output:  # Grading
            self.dashboard_grading()

        tab = widgets.Tab(
            children=[path_selection_output, grading_output, summary_output])
        tab.set_title(0, 'Path')
        tab.set_title(1, 'Grading')
        tab.set_title(2, 'Summary')
        display(tab)
Beispiel #16
0
def display_html_snapshots_widget():
  """Create an ipywidget UI encapsulating all three UIs related to HTML snapshots."""
  if not get_ipython():
    print('The HTML snapshot widget cannot be display in environments other than IPython.') 
    return

  # Configure notebook display preferences to better suit this UI. These display settings
  # will be in effect for all cells in the notebook run after this one is run.
  if pd.__version__.startswith('1'):
    pd.set_option('display.max_colwidth', None)
  else:
    pd.set_option('display.max_colwidth', -1)
  get_ipython().run_cell_magic(
      'javascript',
      '',
      '''// Display cell outputs to full height (no vertical scroll bar)
         IPython.OutputArea.auto_scroll_threshold = 9999;''')

  # Retrieve the workspace metadata for the current user and environment.
  ws_meta = WorkspaceMetadata()
  workspace_names2id = collections.OrderedDict(sorted(
      ws_meta.get_workspace_name_to_id_mapping().items()))
  workspace_names2id_include_readonly = collections.OrderedDict(sorted(
      ws_meta.get_workspace_name_to_id_mapping(include_private_readonly=True).items()))
  workspace_ids2bucket_include_readonly = ws_meta.get_workspace_id_to_bucket_mapping(include_private_readonly=True)
  workspace_paths = {k: WorkspacePaths(workspace_bucket=v)
                     for k, v in workspace_ids2bucket_include_readonly.items()}

  ui_output = widgets.Output()

  ui_tabs = widgets.Tab()
  ui_tabs.children = [create_html_snapshot_widget(ws_names2id=workspace_names2id,
                                                  ws_paths=workspace_paths,
                                                  output=ui_output),
                      create_view_files_widget(ws_names2id=workspace_names2id_include_readonly,
                                               ws_paths=workspace_paths,
                                               output=ui_output),
                      create_view_all_comments_widget(ws_names2id=workspace_names2id_include_readonly,
                                                      ws_paths=workspace_paths,
                                                      output=ui_output)]
  ui_tabs.set_title(title='Create', index=0)
  ui_tabs.set_title(title='View one', index=1)
  ui_tabs.set_title(title='View all', index=2)

  display(ui_tabs, ui_output)
Beispiel #17
0
 def render(self, change=None):
     header = widgets.HTML(
         header_template.render(
             name=self.exp.task,
             status=self.status,
             app_id=self.exp.app_id,
         ), )
     config = get_config()
     if config.ready:
         config_items = config.as_dict().items()
         config_items.sort()
         config_tab = widgets.HTML(
             config_template.render(config=config_items))
     else:
         config_tab = widgets.HTML('Not loaded.')
     tabs = widgets.Tab(children=[config_tab])
     tabs.set_title(0, 'Configuration')
     self.children = [header, tabs]
Beispiel #18
0
def interactive_explore(ls):
    """Create a widget to visually explore a dataset summary.

    Note that the widget will only work when created within a Jupyter notebook.

    Parameters
    ----------
    ls : :class:`~lens.Summary`
        Lens `Summary`.

    Returns
    -------
    :class:`ipywidgets.Widget`
        Jupyter widget with summary plots.
    """
    if not IN_NOTEBOOK:
        message = ('Lens interactive_explore can only be used in a'
                   ' Jupyter notebook')
        logger.error(message)
        raise ValueError(message)
    else:
        # This is a bit of a hack, but it is the only place where the state of
        # plotly initialization is stored. We need to do it because otherwise
        # plotly fails silently if the notebook mode is not initialized.
        if not py.offline.__PLOTLY_OFFLINE_INITIALIZED:
            py.init_notebook_mode()

    tabs = widgets.Tab()
    tabs.children = [
        create_distribution_plot_widget(ls),
        create_cdf_plot_widget(ls),
        create_pairdensity_plot_widget(ls),
        create_correlation_plot_widget(ls)
    ]

    tabs.set_title(0, 'Distribution')
    tabs.set_title(1, 'CDF')
    tabs.set_title(2, 'Pairwise density')
    tabs.set_title(3, 'Correlation matrix')

    return tabs
Beispiel #19
0
def building_admin_view(platform='jupyter'):
    assert platform == 'jupyter' or platform == 'flask'
    project_level_table_view = build_top_table_widget(current_level='project',
                                                      with_subtable=True,
                                                      next_level='member')
    member_level_table_view = build_top_table_widget(current_level='member',
                                                     with_subtable=True,
                                                     next_level='table')
    table_view = build_top_table_widget(current_level='table')
    tab_nest = widgets.Tab()
    tab_nest.children = [
        project_level_table_view, member_level_table_view, table_view
    ]
    tab_nest.set_title(0, 'project-level information')
    tab_nest.set_title(1, 'member-level information')
    tab_nest.set_title(2, 'table-level information')
    if platform == 'flask':
        embed_minimal_html('db_admin.html', views=[tab_nest], title='DB Admin')
        return open('db_admin.html').read()
    else:  # platform == jupyter
        return tab_nest
Beispiel #20
0
def final_output(days, final):
    time = ['MORNING', 'EVENING']
    fields = ['NAME', 'CATEGORY', 'LOCATION', 'PRICE', 'RATING']
    recommendations = ['Recommendation 1:', 'Recommendation 2:']

    box_layout = Layout(
        justify_content='space-between',
        display='flex',
        flex_flow='row',
        align_items='stretch',
    )
    column_layout = Layout(
        justify_content='space-between',
        width='75%',
        display='flex',
        flex_flow='column',
    )
    tab = []
    for i in range(days):
        images = final['image'][i * 4:(i + 1) * 4]
        images = [open(i, "rb").read() for i in images]
        name = [
            re.sub('_', ' ', i).capitalize()
            for i in final['name'][i * 4:(i + 1) * 4]
        ]
        category = [
            re.sub('_', ' ', i).capitalize()
            for i in final['category'][i * 4:(i + 1) * 4]
        ]
        location = [
            "(" + str(i[0]) + "," + str(i[1]) + ")"
            for i in final['location'][i * 4:(i + 1) * 4]
        ]
        price = [str(i) for i in final['price'][i * 4:(i + 1) * 4]]
        rating = [str(i) for i in final['rating'][i * 4:(i + 1) * 4]]
        tab.append(
            VBox(children=[
                HBox(children=[
                    VBox(children=[
                        widgets.HTML(
                            value=f"<b><font color='orange'>{time[0]}</b>"),
                        widgets.HTML(
                            value=
                            f"<b><font color='purple'>{recommendations[0]}</b>"
                        ),
                        widgets.Image(value=images[0],
                                      format='jpg',
                                      width=300,
                                      height=400),
                        widgets.HTML(
                            description=fields[0],
                            value=f"<b><font color='black'>{name[0]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[1],
                            value=f"<b><font color='black'>{category[0]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[2],
                            value=f"<b><font color='black'>{location[0]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[3],
                            value=f"<b><font color='black'>{price[0]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[4],
                            value=f"<b><font color='black'>{rating[0]}</b>",
                            disabled=True)
                    ],
                         layout=column_layout),
                    VBox(children=[
                        widgets.HTML(
                            value=f"<b><font color='orange'>{time[1]}</b>"),
                        widgets.HTML(
                            value=
                            f"<b><font color='purple'>{recommendations[0]}</b>"
                        ),
                        widgets.Image(value=images[2],
                                      format='jpg',
                                      width=300,
                                      height=400),
                        widgets.HTML(
                            description=fields[0],
                            value=f"<b><font color='black'>{name[2]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[1],
                            value=f"<b><font color='black'>{category[2]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[2],
                            value=f"<b><font color='black'>{location[2]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[3],
                            value=f"<b><font color='black'>{price[2]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[4],
                            value=f"<b><font color='black'>{rating[2]}</b>",
                            disabled=True)
                    ],
                         layout=column_layout)
                ],
                     layout=box_layout),
                HBox(children=[
                    VBox(children=[
                        widgets.HTML(
                            value=
                            f"<b><font color='purple'>{recommendations[1]}</b>"
                        ),
                        widgets.Image(value=images[1],
                                      format='jpg',
                                      width=300,
                                      height=400),
                        widgets.HTML(
                            description=fields[0],
                            value=f"<b><font color='black'>{name[1]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[1],
                            value=f"<b><font color='black'>{category[1]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[2],
                            value=f"<b><font color='black'>{location[1]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[3],
                            value=f"<b><font color='black'>{price[1]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[4],
                            value=f"<b><font color='black'>{rating[1]}</b>",
                            disabled=True)
                    ],
                         layout=column_layout),
                    VBox(children=[
                        widgets.HTML(
                            value=
                            f"<b><font color='purple'>{recommendations[1]}</b>"
                        ),
                        widgets.Image(value=images[3],
                                      format='jpg',
                                      width=300,
                                      height=400),
                        widgets.HTML(
                            description=fields[0],
                            value=f"<b><font color='black'>{name[3]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[1],
                            value=f"<b><font color='black'>{category[3]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[2],
                            value=f"<b><font color='black'>{location[3]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[3],
                            value=f"<b><font color='black'>{price[3]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[4],
                            value=f"<b><font color='black'>{rating[3]}</b>",
                            disabled=True)
                    ],
                         layout=column_layout),
                ],
                     layout=box_layout)
            ]))

    tab_recc = widgets.Tab(children=tab)
    for i in range(len(tab_recc.children)):
        tab_recc.set_title(i, str('Day ' + str(i + 1)))
    return tab_recc
Beispiel #21
0
    def build_layout(self, dset_id: str):
        """
        :param dset_id:
        :return:
        """
        all_fields = list(self.get_data(dset_id=dset_id).keys())

        try:
            field_reference = self.skd[dset_id].attrs('target')
        except:
            field_reference = all_fields[0]

        fields_comparison = [all_fields[1]]

        # chart type widget
        self.register_widget(
            chart_type=widgets.RadioButtons(
                options=['individual', 'grouped'],
                value='individual',
                description='Chart Type:'
            )
        )

        # bins widget
        self.register_widget(
            bins=IntSlider(
                description='Bins:',
                min=2, max=10, value=2,
                continuous_update=False
            )
        )

        # fields comparison widget
        self.register_widget(
            xs=widgets.SelectMultiple(
                description='Xs:',
                options=[f for f in all_fields if not f == field_reference],
                value=fields_comparison
            )
        )

        # field reference widget
        self.register_widget(
            y=widgets.Dropdown(
                description='Y:',
                options=all_fields,
                value=field_reference
            )
        )
        # used to internal flow control
        y_changed = [False]

        self.register_widget(
            box_filter_panel=widgets.VBox([
                self._('y'), self._('xs'), self._('bins')
            ])
        )

        # layout widgets
        self.register_widget(
            table=widgets.HTML(),
            chart=widgets.HTML()
        )

        self.register_widget(vbox_chart=widgets.VBox([
            self._('chart_type'), self._('chart')
        ]))

        self.register_widget(
            tab=widgets.Tab(
                children=[
                    self._('box_filter_panel'),
                    self._('table'),
                    self._('vbox_chart')
                ]
            )
        )

        self.register_widget(dashboard=widgets.HBox([self._('tab')]))

        # observe hooks
        def w_y_change(change: dict):
            """
            When y field was changed xs field should be updated and data table
            and chart should be displayed/updated.

            :param change:
            :return:
            """
            # remove reference field from the comparison field list
            _xs = [
                f for f in all_fields
                if not f == change['new']
            ]

            y_changed[0] = True  # flow control variable
            _xs_value = list(self._('xs').value)

            if change['new'] in self._('xs').value:
                _xs_value.pop(_xs_value.index(change['new']))
                if not _xs_value:
                    _xs_value = [_xs[0]]

            self._('xs').options = _xs
            self._('xs').value = _xs_value

            self._display_result(y=change['new'], dset_id=dset_id)

            y_changed[0] = False  # flow control variable

        # widgets registration

        # change tab settings
        self._('tab').set_title(0, 'Filter')
        self._('tab').set_title(1, 'Data')
        self._('tab').set_title(2, 'Chart')

        # data panel
        self._('table').value = '...'

        # chart panel
        self._('chart').value = '...'

        # create observe callbacks
        self._('bins').observe(
            lambda change: (
                self._display_result(bins=change['new'], dset_id=dset_id)
            ), 'value'
        )
        self._('y').observe(w_y_change, 'value')
        # execute display result if 'y' was not changing.
        self._('xs').observe(
            lambda change: (
                self._display_result(xs=change['new'], dset_id=dset_id)
                if not y_changed[0] else None
            ), 'value'
        )
        self._('chart_type').observe(
            lambda change: (
                self._display_result(chart_type=change['new'], dset_id=dset_id)
            ), 'value'
        )
Beispiel #22
0
    def display(self):
        self.update_rm(display_meta=False)

        header = widgets.Label(
            value="Loading Dashboard...",
            layout=self.layout_label,
        )
        display(header)

        if self.enable_datatables:
            init_datatable_mode()
        tables = widgets.Output()
        plots = widgets.Output()
        images = widgets.Output()
        share = widgets.Output()
        latex = widgets.Output()

        main_out = widgets.Output()
        # Display tabs
        tab = widgets.Tab(children=[tables, plots, images, latex, share])
        tab.set_title(0, 'Tables')
        tab.set_title(1, 'Plots')
        tab.set_title(2, 'Images')
        tab.set_title(3, 'Latex')
        tab.set_title(4, 'Share')

        with main_out:
            display(tab)
            tables.clear_output()
            plots.clear_output()
            images.clear_output()
            latex.clear_output()
            share.clear_output()

            # show tabs
            tables_tab(self, tables)
            plots_tab(self, plots)
            images_tab(self, images)
            latex_tab(self, latex)
            share_tab(self, share)

            header.value = 'Dashboard loaded.'

        display(main_out)

        if self.wide_display:
            display(
                HTML("<style>.container { width:100% !important; }</style>"))

        # This makes cell show full height display
        style = """
        <style>
            .output_scroll {
                height: unset !important;
                border-radius: unset !important;
                -webkit-box-shadow: unset !important;
                box-shadow: unset !important;
            }
        </style>
        """
        display(HTML(style))
    def createUI(self):

        # ------------
        # Callbacks
        # ------------
        # Callback for image label dropdown menu
        def dropdown_changed(obj):
            # Note that updating the dropdown label in code (e.g. in the updateUI() function)
            # also triggers this change event. Hence need to check if self.boUpdatingUI is False.
            if obj['type'] == 'change' and obj[
                    'name'] == 'value' and not self.boUpdatingUI:
                imgIndex = int(obj['owner'].description[6:])
                imgObj = self.dataset.images[imgIndex]
                newLabelName = obj['owner'].value
                oldLabelName = imgObj.label

                # physically move image to sub-directory of the new label
                imgObj.label = newLabelName
                imgPathSrc = os.path.join(self.imgOrigDir, oldLabelName,
                                          imgObj.filename)
                imgPathDst = os.path.join(self.imgOrigDir, newLabelName,
                                          imgObj.filename)
                if os.path.exists(imgPathDst):
                    raise Exception(
                        "Cannot more image from {} to {} since the destination already exists."
                        .format(imgPathSrc, imgPathDst))
                shutil.move(imgPathSrc, imgPathDst)
                print("Moved image file from {} to {}.".format(
                    imgPathSrc, imgPathDst))

        # Callback for "zoom" button
        def img_button_pressed(obj):
            imgIndex = int(obj.value)
            imgObj = self.dataset.images[imgIndex]
            self.updateZoomUI(imgObj)

        # Callback for "next images" or "previous images" buttons
        def page_button_pressed(obj):
            self.pageIndex += int(obj.value)
            self.pageIndex = max(0, self.pageIndex)
            self.pageIndex = min(self.pageIndex, len(self.pageImgIndices) - 1)
            self.updateUI()

        # Callback for "image page" slider
        def page_slider_changed(obj):
            try:
                self.pageIndex = int(obj['new']['value'])
                self.updateUI()
            except Exception as e:
                pass

        # Init
        self.boUpdatingUI = False

        # ------------
        # UI - image grid
        # ------------
        self.wImgs = []
        self.wLabels = []
        self.wButtons = []
        wImgLabelButtons = []

        for i in range(self.gridSize[0] * self.gridSize[1]):
            # Initialize images
            wImg = widgets.Image(width=150, description="")
            #wImg = widgets.Image(height=400, description="")
            self.wImgs.append(wImg)

            # Initialize dropdown menus
            wLabel = widgets.Dropdown(options=self.labels,
                                      value=self.labels[0],
                                      text="Image 0",
                                      description="Image 0")
            wLabel.layout.width = '200px'
            wLabel.observe(dropdown_changed, names='value')
            self.wLabels.append(wLabel)

            # Initialize zoom buttons
            wButton = widgets.Button(description="Image id: ", value="")
            wButton.layout.width = "100px"
            wButton.button_style = 'warning'
            wButton.on_click(img_button_pressed)
            self.wButtons.append(wButton)

            # combine into image grid widget
            wImgLabelButton = widgets.VBox(children=[wButton, wImg, wLabel])
            wImgLabelButton.width = '230px'
            wImgLabelButtons.append(wImgLabelButton)

        # Image grid widget
        wGridHBoxes = []
        for r in range(self.gridSize[0]):
            hbox = widgets.HBox(children=[
                wImgLabelButtons[r * self.gridSize[1] + c]
                for c in range(self.gridSize[1])
            ])
            hbox.layout.padding = '10px'
            wGridHBoxes.append(hbox)
        wImgGrid = widgets.VBox(wGridHBoxes)

        # ------------
        # UI - zoom window
        # ------------
        wNextPageButton = widgets.Button(description="Next images", value="1")
        wNextPageButton.value = "1"  # should not be necessary but bug on some jupyter versions otherwise
        wNextPageButton.layout.width = '120px'
        wNextPageButton.button_style = 'primary'
        wNextPageButton.on_click(page_button_pressed)

        wPreviousPageButton = widgets.Button(description="Previous images",
                                             value="-1",
                                             layout=Layout(
                                                 color='white',
                                                 background_color='lightblue'))
        wPreviousPageButton.value = "-1"
        wPreviousPageButton.layout.width = '120px'
        wPreviousPageButton.button_style = 'primary'
        wPreviousPageButton.on_click(page_button_pressed)

        self.wPageSlider = IntSlider(min=0,
                                     max=len(self.pageImgIndices) - 1,
                                     step=1,
                                     value=self.pageIndex,
                                     continuous_update=False,
                                     description='Image page:')
        self.wPageSlider.observe(page_slider_changed)

        self.wZoomHeader = widgets.Text("")
        self.wZoomHeader.layout.width = "100px"
        self.wZoomHeader.layout.color = 'white'
        self.wZoomHeader.layout.background_color = 'orange'
        self.wZoomImg = widgets.Image()
        self.wZoomImg.layout.width = str(self.wZoomImgWidth) + 'px'
        self.wZoomTextArea = widgets.Textarea()
        self.wZoomTextArea.layout.width = '500px'
        self.wZoomTextArea.layout.height = '100px'

        #wZoomButtonSlider = widgets.HBox([widgets.VBox([wNextPageButton, wPreviousPageButton]),
        #                                  self.wPageSlider])  # self.wZoomHeader
        wZoomButtonSlider = widgets.VBox(
            [wNextPageButton, wPreviousPageButton, self.wPageSlider])
        wZoomButtonSlider.layout.width = str(self.wZoomImgWidth +
                                             20) + 'px'  # '420px'

        # ------------
        # UI - final
        # ------------
        annotationUI = widgets.HBox(children=[
            widgets.VBox(children=[
                wZoomButtonSlider, self.wZoomImg, self.wZoomTextArea
            ],
                         width=520), wImgGrid
        ])
        annotationUI.layout.border_color = 'black'
        annotationUI.layout.border_style = 'solid'
        tabsUI = widgets.Tab(children=[annotationUI])
        tabsUI.set_title(0, 'Image Annotation')

        # Update UI with actual images
        self.updateUI()
        return (tabsUI)
Beispiel #24
0
def select(table_id = None, 
           language = 'en', 
           base_url = 'http://data.ssb.no/api/v0', 
           full_url = None):
    """
    Selects a table based on the table_id and returns a widget container 
    in which the user can select the set of variables and values to be 
    included in the final table.
    
    
    Example
    --------
    box = select(table_id = '10714')
    
    
    Parameters
    ----------    
    
        table_id : string 
            the id of the desired table
         
        language: string
            language for table
            'en' (default, English) 
            'no' (Norwegian): 
            language for table
        
        base_url: string.
            base url locating the table (not including table_id)
        
        full_url: string
            the full url to the table
    """
        
    # get table_id not full url was specified 
    if full_url is None:
        full_url = '{base_url}/{language}/table/{table_id}'.format(
                    base_url = base_url, 
                    language = language, 
                    table_id = table_id)
        
    table_info = pd.read_json(full_url)
    table_title = table_info.iloc[0,0]

    # get a list with dictionaries containing information about each variable
    variables = get_variables(table_id = table_id, 
                              language = language,
                              base_url = base_url,
                              full_url = full_url)
    
    # get number of variables (ok, childish approach, can be simplified!)
    nvars = len(variables)
    var_list = list(range(nvars))
    
    # a list of dictionaries of the values available for each variable
    option_list = [OrderedDict(zip(variables[var]['valueTexts'], 
                                   variables[var]['values'])) 
                   for var in var_list]
    
    # create a selection widget for each variable
    # todo: skip widget or make it invisible if there is only one option?
    # todo: make first alternative a default selection initially for all tables?
    # todo: add buttons for selecting "all", "latest" , "first" and "none"
                         
    selection_widgets = [widgets.widget_selection.SelectMultiple(
                            options = option_list[var], 
                            height = 400, 
                            width = 500) 
                         for var in var_list]
    
    # put all the widgets in a container
    variables_container = widgets.Tab(selection_widgets)

    # label each container with the variable label 
    for var in var_list:
        title = str(variables[var]['text'])
        variables_container.set_title(var, title)
    
    # build widgets and put in one widget container
    headline = widgets.Label(value = table_title, color = 'blue')
    
    endline = widgets.Label(value = '''Select category and click on elements 
        to be included in the table (CTRL-A selects "all")''')
    
    url_text = widgets.Label(value = full_url)
    
    selection_container = widgets.VBox([headline, 
                                        endline, 
                                        variables_container, 
                                        url_text])
    
    selection_container.layout.border = '3px grey solid'
    # may include a "click here when finished" just to make it more intuitive?
    return selection_container
Beispiel #25
0
def interact(obj):
    tab = widgets.Tab()
    base_style = widgets.ButtonStyle()
    selected_style = widgets.ButtonStyle(button_color='#DDFFDD',
                                         font_weight='bold')

    if isinstance(obj, hl.Table):
        glob = widgets.Button(description='globals',
                              layout=widgets.Layout(width='150px',
                                                    height='30px'))
        rows = widgets.Button(description='rows',
                              layout=widgets.Layout(width='150px',
                                                    height='200px'))
        rows.style = selected_style

        globals_frames = []
        globals_frames.append(
            widgets.HTML(
                f'<p><big>Global fields, with one value in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_globals", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.annotate_globals")}: '
                f'add new global fields.</li>'
                f'</ul>'))
        append_struct_frames(obj.globals.dtype, globals_frames)

        row_frames = []
        row_frames.append(
            widgets.HTML(
                f'<p><big>Row fields, with one record per row of the table.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.annotate")}: '
                f'add new fields.</li>'
                f'<li>{html_link("filter", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.filter")}: '
                f'filter rows of the table.</li>'
                f'<li>{html_link("aggregate", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.aggregate")}: '
                f'aggregate over rows to produce a single value.</li>'
                f'</ul>'))
        if len(obj.key) > 0:
            row_frames.append(
                widgets.HTML(f'<p><big>Key: {list(obj.key)}<big><p>'))
        append_struct_frames(obj.row.dtype, row_frames)

        tab.children = [
            widgets.VBox(frames) for frames in [globals_frames, row_frames]
        ]
        tab.set_title(0, 'globals')
        tab.set_title(1, 'row')
        tab.selected_index = 1

        box = widgets.VBox([glob, rows])
        buttons = [glob, rows]
    else:
        assert isinstance(obj, hl.MatrixTable)
        glob = widgets.Button(description='globals',
                              layout=widgets.Layout(width='65px',
                                                    height='30px'))
        cols = widgets.Button(description='cols',
                              layout=widgets.Layout(width='200px',
                                                    height='30px'))
        rows = widgets.Button(description='rows',
                              layout=widgets.Layout(width='65px',
                                                    height='200px'))
        entries = widgets.Button(description='entries',
                                 layout=widgets.Layout(width='200px',
                                                       height='200px'))
        entries.style = selected_style

        globals_frames = []
        globals_frames.append(
            widgets.HTML(
                f'<p><big>Global fields, with one value in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_globals()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_globals")}: '
                f'add new global fields.</li>'
                f'</ul>'))
        append_struct_frames(obj.globals.dtype, globals_frames)

        row_frames = []
        row_frames.append(
            widgets.HTML(
                f'<p><big>Row fields, with one record per row in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_rows")}: '
                f'add new row fields. This method supports {html_link("aggregation", "https://hail.is/docs/0.2/aggregators.html")}, '
                f'aggregating over entries to compute one result per row, e.g. computing the mean depth per variant.</li>'
                f'<li>{html_link("filter_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_rows")}: '
                f'filter rows in the matrix table.</li>'
                f'<li>{html_link("aggregate_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_rows")}: '
                f'aggregate over rows (not including entries or columns) to produce a single value, e.g. counting the number of loss-of-function variants.</li>'
                f'<li>{html_link("rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.rows")}: '
                f'return the rows as a Hail {html_link("Table", "https://hail.is/docs/0.2/hail.Table.html")}.</li>'
                f'</ul>'))
        if len(obj.row_key) > 0:
            row_frames.append(
                widgets.HTML(f'<p><big>Row key: {list(obj.row_key)}<big><p>'))
        append_struct_frames(obj.row.dtype, row_frames)

        col_frames = []
        col_frames.append(
            widgets.HTML(
                f'<p><big>Column fields, with one record per column in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_cols")}: '
                f'add new column fields. This method supports {html_link("aggregation", "https://hail.is/docs/0.2/aggregators.html")}, '
                f'aggregating over entries to compute one result per column, e.g. computing the mean depth per sample.</li>'
                f'<li>{html_link("filter_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_cols")}: '
                f'filter columns in the matrix table.</li>'
                f'<li>{html_link("aggregate_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_cols")}: '
                f'aggregate over columns (not including entries or rows) to produce a single value, e.g. counting the number of samples with case status.</li>'
                f'<li>{html_link("cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.cols")}: '
                f'return the columns as a Hail {html_link("Table", "https://hail.is/docs/0.2/hail.Table.html")}.'
                f'</li>'
                f'</ul>'))
        if len(obj.col_key) > 0:
            col_frames.append(
                widgets.HTML(
                    f'<p><big>Column key: {list(obj.col_key)}<big><p>'))
        append_struct_frames(obj.col.dtype, col_frames)

        entry_frames = []
        entry_frames.append(
            widgets.HTML(
                f'<p><big>Entry fields, with one record per (row, column) pair in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_entries()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_entries")}: '
                f'add new entry fields.</li>'
                f'<li>{html_link("filter_entries()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_entries")}: '
                f'filter entries in the matrix table, removing them from downstream operations, like aggregations.</li>'
                f'<li>{html_link("aggregate_entries", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_entries")}: '
                f'aggregate over entries to produce a single value, e.g. computing mean depth across an entire dataset.</li>'
                f'</ul>'))
        append_struct_frames(obj.entry.dtype, entry_frames)

        tab.children = [
            widgets.VBox(frames) for frames in
            [globals_frames, row_frames, col_frames, entry_frames]
        ]
        tab.set_title(0, 'globals')
        tab.set_title(1, 'row')
        tab.set_title(2, 'col')
        tab.set_title(3, 'entry')
        tab.selected_index = 3

        box = widgets.VBox(
            [widgets.HBox([glob, cols]),
             widgets.HBox([rows, entries])])
        buttons = [glob, rows, cols, entries]

    selection_handler = widgets.IntText(tab.selected_index)
    button_idx = dict(zip(buttons, range(len(buttons))))

    def handle_selection(x):
        if x['name'] == 'value' and x['type'] == 'change':
            buttons[x['old']].style = base_style
            selection = x['new']
            buttons[selection].style = selected_style
            tab.selected_index = selection

    selection_handler.observe(handle_selection)
    widgets.jslink((tab, 'selected_index'), (selection_handler, 'value'))

    def button_action(b):
        selection_handler.value = button_idx[b]

    for button in button_idx:
        button.on_click(button_action)

    display(box, tab)
    def create_ui(self):

        # ------------
        # Callbacks
        # ------------
        # Callback for image label dropdown menu
        def dropdown_changed(obj):
            # Note that updating the dropdown label in code (e.g. in the update_ui() function)
            # also triggers this change event. Hence need to check if self.bo_updating_ui is False.
            if obj['type'] == 'change' and obj[
                    'name'] == 'value' and not self.bo_updating_ui:
                img_index = int(obj['owner'].description[6:])
                new_label = obj['owner'].value
                self.dataset.change_label_for_image(
                    self.dataset.images[img_index], new_label)

        # Callback for "zoom" button
        def img_button_pressed(obj):
            img_index = int(obj.value)
            img_obj = self.dataset.images[img_index]
            self.update_zoom_ui(img_obj, img_index)

        # Callback for "next images" or "previous images" buttons
        def page_button_pressed(obj):
            self.page_index += int(obj.value)
            self.page_index = max(0, self.page_index)
            self.page_index = min(self.page_index,
                                  len(self.page_img_indices) - 1)
            self.update_ui()

        # Callback for "image page" slider
        def page_slider_changed(obj):
            try:
                self.page_index = int(obj['new']['value'])
                self.update_ui()
            except Exception as e:
                pass

        # Init
        self.bo_updating_ui = False

        # ------------
        # UI - image grid
        # ------------
        self.w_imgs = []
        self.w_labels = []
        self.w_buttons = []
        w_img_label_buttons = []

        for i in range(self.grid_size[0] * self.grid_size[1]):
            # Initialize images
            w_img = widgets.Image(width=200, description="")
            self.w_imgs.append(w_img)

            # Initialize dropdown menus
            w_label = widgets.Dropdown(
                options=self.label_options,
                value=self.label_options[self.labels[0].name],
                text="Image 0",
                description="Image 0")
            w_label.layout.width = '200px'
            w_label.observe(dropdown_changed, names='value')
            self.w_labels.append(w_label)

            # Initialize zoom buttons
            w_button = widgets.Button(description="Image id: ", value="")
            w_button.layout.width = "100px"
            w_button.button_style = 'warning'
            w_button.on_click(img_button_pressed)
            self.w_buttons.append(w_button)

            # combine into image grid widget
            w_img_label_button = widgets.VBox(
                children=[w_button, w_img, w_label])
            w_img_label_button.width = '230px'
            w_img_label_buttons.append(w_img_label_button)

        # Image grid widget
        w_grid_HBoxes = []
        for r in range(self.grid_size[0]):
            hbox = widgets.HBox(children=[
                w_img_label_buttons[r * self.grid_size[1] + c]
                for c in range(self.grid_size[1])
            ])
            hbox.layout.padding = '10px'
            w_grid_HBoxes.append(hbox)
        w_img_grid = widgets.VBox(w_grid_HBoxes)

        # ------------
        # UI - zoom window
        # ------------
        w_next_page_button = widgets.Button(description="Next images",
                                            value="1")
        w_next_page_button.value = "1"  # should not be necessary but bug on some jupyter versions otherwise
        w_next_page_button.layout.width = '120px'
        w_next_page_button.button_style = 'primary'
        w_next_page_button.on_click(page_button_pressed)

        w_previous_page_button = widgets.Button(
            description="Previous images",
            value="-1",
            layout=Layout(color='white', background_color='lightblue'))
        w_previous_page_button.value = "-1"
        w_previous_page_button.layout.width = '120px'
        w_previous_page_button.button_style = 'primary'
        w_previous_page_button.on_click(page_button_pressed)

        self.w_page_slider = IntSlider(min=0,
                                       max=len(self.page_img_indices) - 1,
                                       step=1,
                                       value=self.page_index,
                                       continuous_update=False,
                                       description='Image page:')
        self.w_page_slider.observe(page_slider_changed)

        self.w_zoom_header = widgets.Text("")
        self.w_zoom_header.layout.width = "100px"
        self.w_zoom_header.layout.color = 'white'
        self.w_zoom_header.layout.background_color = 'orange'
        self.w_zoom_img = widgets.Image()
        self.w_zoom_img.layout.width = '500px'
        self.w_zoom_text_area = widgets.Textarea()
        self.w_zoom_text_area.layout.width = '500px'
        self.w_zoom_text_area.layout.height = '100px'

        w_zoom_button_slider = widgets.HBox([
            widgets.VBox([w_next_page_button, w_previous_page_button]),
            self.w_page_slider
        ])  # self.w_zoom_header
        w_zoom_button_slider.layout.width = '420px'

        # ------------
        # UI - final
        # ------------
        annotation_ui = widgets.HBox(children=[
            widgets.VBox(children=[
                w_zoom_button_slider, self.w_zoom_img, self.w_zoom_text_area
            ],
                         width=520), w_img_grid
        ])
        annotation_ui.layout.border_color = 'black'
        annotation_ui.layout.border_style = 'solid'
        tabs_ui = widgets.Tab(children=[annotation_ui])
        tabs_ui.set_title(0, 'Image Annotation')

        # Update UI with actual images
        self.update_ui()
        return (tabs_ui)
Beispiel #27
0
    def old_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_box_h_1 = widgets.HBox([d1_button_prev, d1_button_next])
        ###
        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
        d2_vbox_childs = []
        ##
        ###
        d2_button_next = widgets.Button(description='next measurement')
        d2_button_prev = widgets.Button(description='prev measurement')

        self.d2_dropdown_fnames = widgets.Dropdown(
            options=[
                1
            ],  #[i.name for i in self.controller.data.dataset2.path2data_list],
            value=1,  #self.controller.data.dataset2.path2active.name,
            #     description='N',
            disabled=False,
        )

        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

        self.accordeon_assigned = widgets.Valid(
            value=False,
            description='bound?',
        )

        self.dropdown_popssn = widgets.Dropdown(
            options=['00', '14', '18'],
            # value='2',
            description='popssn',
            disabled=False,
        )

        self.inttext_deltat = widgets.IntText(value=0,
                                              description='deltat',
                                              disabled=False)
        self.inttext_deltat.observe(self.on_inttext_deltat)

        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_bind_measurements = widgets.ToggleButton(
            description='bind/unbind measurements')
        # button_bind_measurements.on_click(self.deprecated_on_button_bind_measurements)
        self.button_bind_measurements.observe(self.on_button_bind_measurements)

        accordon_box = widgets.VBox([
            self.accordeon_assigned, self.dropdown_popssn, self.inttext_deltat,
            self.dropdown_gps_bar_bad, self.button_bind_measurements
        ])
        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()
Beispiel #28
0
def full_riemann_interactive(
        ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
    """Plots interactive full riemann solution with phase plane plot."""

    # Create plot function for interact
    pp_plot = full_riemann_solution_plot()

    # Declare all widget sliders
    t_widget = widgets.FloatSlider(value=0,
                                   min=0.0,
                                   max=1.0,
                                   description='$t$')
    ql1_widget = widgets.FloatSlider(value=ql[0],
                                     min=0.01,
                                     max=50.0,
                                     description='$p_l$')
    ql2_widget = widgets.FloatSlider(value=ql[1],
                                     min=-30,
                                     max=30.0,
                                     description='$u_l$')
    qr1_widget = widgets.FloatSlider(value=qr[0],
                                     min=0.01,
                                     max=50.0,
                                     description='$p_r$')
    qr2_widget = widgets.FloatSlider(value=qr[1],
                                     min=-30,
                                     max=30.0,
                                     description='$u_r$')
    rho_widget = widgets.FloatSlider(value=rho,
                                     min=0.01,
                                     max=10.0,
                                     description=r'$\rho$')
    bulk_widget = widgets.FloatSlider(value=bulk,
                                      min=0.01,
                                      max=10.0,
                                      description='$K$')
    xmin_widget = widgets.BoundedFloatText(value=0.0000001,
                                           description='$p_{min}:$')
    xmax_widget = widgets.FloatText(value=50, description='$p_{max}:$')
    ymin_widget = widgets.FloatText(value=-30, description='$u_{min}:$')
    ymax_widget = widgets.FloatText(value=30, description='$u_{max}:$')
    which_char_widget = widgets.Dropdown(options=[None, 1, 2],
                                         description='Characs.')

    # Allow for dependent widgets to update
    def update_xmin(*args):
        ql1_widget.min = xmin_widget.value
        qr1_widget.min = xmin_widget.value

    def update_xmax(*args):
        ql1_widget.max = xmax_widget.value
        qr1_widget.max = xmax_widget.value

    def update_ymin(*args):
        ql2_widget.min = ymin_widget.value
        qr2_widget.min = ymin_widget.value

    def update_ymax(*args):
        ql2_widget.max = ymax_widget.value
        qr2_widget.max = ymax_widget.value

    xmin_widget.observe(update_xmin, 'value')
    xmax_widget.observe(update_xmax, 'value')
    ymin_widget.observe(update_ymin, 'value')
    ymax_widget.observe(update_ymax, 'value')

    # Organize slider widgets into boxes
    qleftright = widgets.VBox([
        widgets.HBox([t_widget, which_char_widget]),
        widgets.HBox([ql1_widget, ql2_widget, rho_widget]),
        widgets.HBox([qr1_widget, qr2_widget, bulk_widget])
    ])
    plot_opts = widgets.VBox([
        widgets.HBox([xmin_widget, xmax_widget]),
        widgets.HBox([ymin_widget, ymax_widget])
    ])

    # Set up interactive GUI (tab style)
    interact_gui = widgets.Tab(children=[qleftright, plot_opts])
    interact_gui.set_title(0, 'Left and right states')
    interact_gui.set_title(1, 'Plot options')

    # Define interactive widget and run GUI
    ppwidget = interact(pp_plot,
                        t=t_widget,
                        pl=ql1_widget,
                        ul=ql2_widget,
                        pr=qr1_widget,
                        ur=qr2_widget,
                        rho=rho_widget,
                        bulk=bulk_widget,
                        which_char=which_char_widget,
                        xmin=xmin_widget,
                        xmax=xmax_widget,
                        ymin=ymin_widget,
                        ymax=ymax_widget)
    try:
        ppwidget.widget.close()
        display(interact_gui)
        display(ppwidget.widget.out)
    except:
        pass
    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')
Beispiel #30
0
    def display(self):
        self.update_rm()

        # Select Exp Group
        l_exp_group = widgets.Label(
            value="Select exp_group",
            layout=self.layout_label,
        )

        exp_group_list = list(self.rm_original.exp_groups.keys())
        exp_group_selected = 'all'
        if self.vars.get('exp_group', 'all') in exp_group_list:
            exp_group_selected = self.vars.get('exp_group', 'all')

        d_exp_group = widgets.Dropdown(
            options=exp_group_list,
            value=exp_group_selected,
            layout=self.layout_dropdown,
        )
        self.rm_original.exp_list_all = self.rm_original.exp_groups.get(
            d_exp_group.value, 'all')
        l_n_exps = widgets.Label(
            value='Total Exps %d' % len(self.rm_original.exp_list_all),
            layout=self.layout,
        )

        def on_group_change(change):
            if change['type'] == 'change' and change['name'] == 'value':
                self.rm_original.exp_list_all = self.rm_original.exp_groups[
                    change['new']]
                l_n_exps.value = 'Total Exps %d' % len(
                    self.rm_original.exp_list_all)

        d_exp_group.observe(on_group_change)

        display(
            widgets.VBox([
                l_exp_group,
                widgets.HBox([d_exp_group, l_n_exps, self.t_filterby_list])
            ]))

        if self.enable_datatables:
            init_datatable_mode()
        tables = widgets.Output()
        plots = widgets.Output()
        images = widgets.Output()
        share = widgets.Output()
        latex = widgets.Output()

        main_out = widgets.Output()
        # Display tabs
        tab = widgets.Tab(children=[tables, plots, images, latex, share])
        tab.set_title(0, 'Tables')
        tab.set_title(1, 'Plots')
        tab.set_title(2, 'Images')
        tab.set_title(3, 'Latex')
        tab.set_title(4, 'Share')

        with main_out:
            display(tab)
            tables.clear_output()
            plots.clear_output()
            images.clear_output()
            latex.clear_output()
            share.clear_output()

            # show tabs
            tables_tab(self, tables)
            plots_tab(self, plots)
            images_tab(self, images)
            latex_tab(self, latex)
            share_tab(self, share)

        display(main_out)

        if self.wide_display:
            display(
                HTML("<style>.container { width:100% !important; }</style>"))

        # This makes cell show full height display
        style = """
        <style>
            .output_scroll {
                height: unset !important;
                border-radius: unset !important;
                -webkit-box-shadow: unset !important;
                box-shadow: unset !important;
            }
        </style>
        """
        display(HTML(style))