Example #1
0
 def _contour_folder(self, folder):
     control = Button(description=' Contours', icon='dot-circle-o')
     def _cshow(b):
         for scn in self.active(): scn.cont_show = not scn.cont_show
     control.on_click(_cshow)
     content = _ListDict([
         ('fopts', folder['fopts']),
         ('axis', Dropdown(options=['x', 'y', 'z'], value='z')),
         ('num', IntSlider(description='N', min=5, max=20,
                           value=10, step=1)),
         ('lim', IntRangeSlider(description='10**Limits', min=-8,
                                max=0, step=1, value=[-7, -1])),
         ('val', FloatSlider(description='Value',
                             min=-5, max=5, value=0))])
     def _cont_axis(c):
         for scn in self.active(): scn.cont_axis = c.new
     def _cont_num(c):
         for scn in self.active(): scn.cont_num = c.new
     def _cont_lim(c):
         for scn in self.active(): scn.cont_lim = c.new
     def _cont_val(c):
         for scn in self.active(): scn.cont_val = c.new
     content['axis'].observe(_cont_axis, names='value')
     content['num'].observe(_cont_num, names='value')
     content['lim'].observe(_cont_lim, names='value')
     content['val'].observe(_cont_val, names='value')
     contour = Folder(control, content)
     folder.insert(2, 'contour', contour, active=True, update=True)
class ImageDownloader():
    """
    Displays a widget that allows searching and downloading images from google images search
    in a Jupyter Notebook or Lab.
    """
    def __init__(self, path:Union[Path,str]='data'):
        "Setup path to save images to, init the UI, and render the widgets."
        self._path = Path(path)
        self._ui = self._init_ui()
        self.render()

    def _init_ui(self) -> VBox:
        "Initialize the widget UI and return the UI."
        self._search_input = Text(placeholder="What images to search for?")
        self._count_input = BoundedIntText(placeholder="How many pics?", value=10, min=1, max=5000, step=1,
                                           layout=Layout(width='60px'))
        self._size_input = Dropdown(options= _img_sizes.keys(), value='>400*300', layout=Layout(width='120px'))
        self._download_button = Button(description="Search & Download", icon="download", layout=Layout(width='200px'))
        self._download_button.on_click(self.on_download_button_click)
        self._output = Output()
        self._controls_pane  = HBox([self._search_input, self._count_input, self._size_input, self._download_button],
                                    layout=Layout(width='auto', height='40px'))
        self._heading = ""
        self._download_complete_heading = "<h3>Download complete. Here are a few images</h3>"
        self._preview_header = widgets.HTML(self._heading, layout=Layout(height='60px'))
        self._img_pane = Box(layout=Layout(display='inline'))
        return VBox([self._controls_pane, self._preview_header, self._img_pane])

    def render(self) -> None:
        clear_output()
        display(self._ui)

    def clear_imgs(self) -> None:
        "Clear the widget's images preview pane."
        self._preview_header.value = self._heading
        self._img_pane.children = tuple()

    def validate_search_input(self) -> bool:
        "Check if input value is empty."
        input = self._search_input
        if input.value == str(): input.layout = Layout(border="solid 2px red", height='auto')
        else:                    self._search_input.layout = Layout()
        return input.value != str()

    def on_download_button_click(self, btn) -> None:
        "Download button click handler: validate search term and download images."
        term = self._search_input.value
        limit = int(self._count_input.value)
        size = self._size_input.value
        if not self.validate_search_input(): return
        self.clear_imgs()
        downloaded_images = download_google_images(self._path, term, n_images=limit, size=size)
        self.display_images_widgets(downloaded_images[:min(limit, 12)])
        self._preview_header.value = self._download_complete_heading
        self.render()

    def display_images_widgets(self, fnames:list) -> None:
        "Display a few preview images in the notebook"
        imgs = [widgets.Image(value=open(f, 'rb').read(), width='200px') for f in fnames]
        self._img_pane.children = tuple(imgs)
class StaticFigureWrapper() :
    def __init__(self,fdpi=300,fsize=(4,3),flabel="fig") :
        # Set local variables
        self.fdpi=fdpi
        self.fsize=fsize
        self.flabel=flabel
        
        # Generate figure
        self.fig = figure(dpi=self.fdpi,figsize=self.fsize)
        close(self.fig)
        
        # Generate plot axes for the figure
        self.ax=self.fig.add_subplot(111)
        
        # Create an html widget for the figure picture
        self.outputHTML = HTML()
        
        # Create save figure widget
        self.btn = Button(description = 'Save %s' % flabel)
        self.btn.on_click(self.btnfunc)
    
    def btnfunc(self,btn): 
        self.fig.savefig('%s.png' % self.flabel , ext="png",bbox_inches='tight',dpi=self.fdpi)
    
    def plot_to_html(self):
        # write image data to a string buffer and get the PNG image bytes
        self.buf = BytesIO()
        self.fig.savefig(self.buf, format="png",bbox_inches='tight')
        self.buf.seek(0)
        return """<img src='data:image/png;base64,{}'/>""".format(b64encode(self.buf.getvalue()))
    
    def render(self) :
        self.outputHTML.value=self.plot_to_html()
        return VBox([self.outputHTML,self.btn],align="center")
Example #4
0
    def _init_gui(self, **kwargs):
        nframes = kwargs.pop("nframes", 1)
        fields = kwargs.pop("fields", None)
        tensors = kwargs.pop("tensors", None)
        mainopts = super(UniverseWidget, self)._init_gui(**kwargs)
        atoms = Button(description=' Fill', icon='adjust', layout=_wlo)
        axis = Button(description=' Axis', icon='arrows-alt', layout=_wlo)

        def _atom_3d(b):
            for scn in self.active(): scn.atom_3d = not scn.atom_3d

        def _axis(b):
            for scn in self.active(): scn.axis = not scn.axis

        atoms.on_click(_atom_3d)
        axis.on_click(_axis)
        atoms.active = True
        atoms.disabled = False
        axis.active = True
        atoms.disabled = False
        mainopts.update([('atom_3d', atoms), ('axis', axis),
                         ('frame', self._frame_folder(nframes))])
        if fields is not None:
            folder = self._field_folder(fields, **kwargs)
            self._iso_folder(folder)
            self._contour_folder(folder)
            folder.pop('fopts')
            mainopts.update([('field', folder)])

        if tensors is not None:
            mainopts.update([('tensor', self._tensor_folder())])

        return mainopts
Example #5
0
    def _wrapper(self, *args, **kwargs):  # pylint: disable=too-many-locals
        result = func(self, *args, **kwargs)

        if isinstance(result, rockets.RequestTask) and in_notebook():
            from ipywidgets import FloatProgress, Label, HBox, VBox, Button
            from IPython.display import display

            progress = FloatProgress(min=0, max=1, value=0)
            label = Label(value='')
            button = Button(description='Cancel')
            box = VBox([label, HBox([progress, button])])
            display(box)

            def _on_cancel(value):  # pylint: disable=unused-argument
                result.cancel()

            def _on_progress(value):
                progress.value = value.amount
                label.value = value.operation

            def _on_done(task):  # pylint: disable=unused-argument
                box.close()

            button.on_click(_on_cancel)
            result.add_progress_callback(_on_progress)
            result.add_done_callback(_on_done)

        return result
Example #6
0
    def _make_button_repr_control(self, component_slider, repr_slider, repr_selection):
        button_refresh = Button(description=' Refresh', tooltip='Get representation info', icon='fa-refresh')
        button_center_selection = Button(description=' Center', tooltip='center selected atoms',
                icon='fa-bullseye')
        button_center_selection._ngl_name = 'button_center_selection'
        button_hide = Button(description=' Hide',
                icon='fa-eye-slash',
                tooltip='Hide/Show current representation')
        button_remove = Button(description=' Remove',
                icon='fa-trash',
                tooltip='Remove current representation')
        button_repr_parameter_dialog = Button(description=' Dialog',
                tooltip='Pop up representation parameters control dialog')

        @button_refresh.on_click
        def on_click_refresh(button):
            self._refresh(component_slider, repr_slider)

        @button_center_selection.on_click
        def on_click_center(center_selection):
            self._view.center_view(selection=repr_selection.value,
                                   component=component_slider.value)

        @button_hide.on_click
        def on_click_hide(button_hide):
            component=component_slider.value
            repr_index=repr_slider.value

            if button_hide.description == 'Hide':
                hide = True
                button_hide.description = 'Show'
            else:
                hide = False
                button_hide.description = 'Hide'

            self._view._remote_call('setVisibilityForRepr',
                                    target='Widget',
                                    args=[component, repr_index, not hide])

        @button_remove.on_click
        def on_click_remove(button_remove):
            self._view._remove_representation(component=component_slider.value,
                                              repr_index=repr_slider.value)
            self._view._request_repr_parameters(component=component_slider.value,
                                                repr_index=repr_slider.value)

        @button_repr_parameter_dialog.on_click
        def on_click_repr_dialog(_):
            from nglview.widget_box import DraggableBox
            if self.widget_repr_parameters is not None and self.widget_repr_choices:
                self.widget_repr_parameters_dialog = DraggableBox([self.widget_repr_choices,
                                     self.widget_repr_parameters])
                self.widget_repr_parameters_dialog._ipython_display_()
                self.widget_repr_parameters_dialog._dialog = 'on'

        bbox = _make_autofit(HBox([button_refresh, button_center_selection,
                                   button_hide, button_remove,
                                   button_repr_parameter_dialog]))
        return bbox
Example #7
0
    def interactive_correlations(self):
        def do_interact(data_type='expression',
                        sample_subset=self.default_sample_subsets,
                        feature_subset=self.default_feature_subset,
                        metric='euclidean', method='average',
                        list_link='',
                        scale_fig_by_data=True,
                        fig_width='', fig_height='', featurewise=False):

            for k, v in locals().iteritems():
                if k == 'self':
                    continue
                sys.stdout.write('{} : {}\n'.format(k, v))

            if feature_subset != "custom" and list_link != "":
                raise ValueError(
                    "set feature_subset to \"custom\" to use list_link")

            if feature_subset == "custom" and list_link == "":
                raise ValueError("use a custom list name please")

            if feature_subset == 'custom':
                feature_subset = list_link
            elif feature_subset not in self.default_feature_subsets[data_type]:
                warnings.warn("This feature_subset ('{}') is not available in "
                              "this data type ('{}'). Falling back on all "
                              "features.".format(feature_subset, data_type))
            return self.plot_correlations(
                sample_subset=sample_subset, feature_subset=feature_subset,
                data_type=data_type, scale_fig_by_data=scale_fig_by_data,
                method=method, metric=metric, featurewise=featurewise)

        feature_subsets = Interactive.get_feature_subsets(self,
                                                          ['expression',
                                                           'splicing'])
        method = ('average', 'weighted', 'single', 'complete', 'ward')
        metric = ('euclidean', 'seuclidean', 'sqeuclidean', 'chebyshev',
                  'cosine', 'cityblock', 'mahalonobis', 'minowski', 'jaccard')
        gui = interact(do_interact,
                       data_type=('expression', 'splicing'),
                       sample_subset=self.default_sample_subsets,
                       feature_subset=feature_subsets,
                       metric=metric,
                       method=method,
                       featurewise=False)

        def save(w):
            filename, extension = os.path.splitext(savefile.value)
            self.maybe_make_directory(savefile.value)
            gui.widget.result.savefig(savefile.value,
                                      format=extension.lstrip('.'))

        savefile = Text(description='savefile',
                        value='figures/correlations.pdf')
        save_widget = Button(description='save')
        gui.widget.children = list(gui.widget.children) + [savefile,
                                                           save_widget]
        save_widget.on_click(save)
        return gui
Example #8
0
 def _iso_folder(self, folder):
     isos = Button(description=' Isosurfaces', icon='cube')
     def _fshow(b):
         for scn in self.active(): scn.field_show = not scn.field_show
     isos.on_click(_fshow)
     isofolder = Folder(isos, _ListDict([
         ('fopts', folder['fopts']),
         ('alpha', folder.pop('alpha')),
         ('iso', folder.pop('iso'))]))
     isofolder.move_to_end('alpha', 'iso')
     folder.insert(1, 'iso', isofolder, active=True)
Example #9
0
 def _init_gui(self, **kwargs):
     """Initialize generic GUI controls and observe callbacks."""
     mainopts = super(DemoContainer, self)._init_gui()
     geom = Button(icon='gear', description=' Mesh', layout=_wlo)
     def _geom(b):
         for scn in self.active():
             scn.geom = not scn.geom
     geom.on_click(_geom)
     mainopts.update([('geom', geom),
                      ('field', self._field_folder(**kwargs))])
     return mainopts
Example #10
0
def savebutton(fig, figpath, figname, transparent=True):
    # Implement a 'save figure' button
    if os.path.isfile(figpath + figname):
        button = Button(description='Overwrite existing figure?')
    else:
        button = Button(description='Save figure.')

    display(button)

    # The save button
    # TODO: https://stackoverflow.com/questions/10532614/can-matplotlib-add-metadata-to-saved-figures
    def clicketh(b):
        # http://stackoverflow.com/questions/24791709/save-a-plot-resulting-from-a-function-matplotlib-python
        fig.savefig(figpath + figname, transparent=transparent)

    button.on_click(clicketh)
Example #11
0
def gen_figure(msids, group_name):
    def select_next_msid(junk):
        current_msid = msid_select.value
        options = msid_select.options
        i = options.index(current_msid)
        if i < len(options) - 1:
            msid_select.value=options[i + 1]

    dummyfig = plt.figure(facecolor=[1,1,1],figsize=(14,8))
    msid_select = Select(description='MSID:',options=msids, visible=True, padding=4)
    button_next_msid = Button(description='Next', padding=4)
    button_next_msid.on_click(select_next_msid)
    msid_select_group = HBox(children=[msid_select, button_next_msid])

    latest = DateTime().date
    t1 = Text(description='Start Date:', value='2000:001:00:00:00.000', visible=True, padding=4)
    t2 = Text(description='Stop Date:', value=latest, visible=True, padding=4)
    time_select = Box(children=[t1, t2])
    page1 = HBox(children=[msid_select_group, time_select])

    wL = Checkbox(description='Plot Warning Low', value=False, visible=True, padding=4)
    cL = Checkbox(description='Plot Caution Low', value=False, visible=True, padding=4)
    cH = Checkbox(description='Plot Caution High', value=True, visible=True, padding=4)
    wH = Checkbox(description='Plot Warning High', value=True, visible=True, padding=4)
    low_select = Box(children=[wL, cL])
    high_select = Box(children=[wH, cH])
    page2 = HBox(children=[high_select, low_select])

    stat_select = Select(description='Stat:',options=('daily', '5min', 'None'), visible=True, padding=4)
    filter_bads = Checkbox(description='Filter Bad Times:', value=True, visible=True, padding=4)
    group_select = Select(description='Group Name:',options=['sc', 'tel', 'isim'], visible=True, value=group_name, padding=4)
    left_select = Box(children=[stat_select, filter_bads])
    page3 = HBox(children=[left_select, group_select], description='Misc.')

    q = interactive(plot_msid_interactive, msid=msid_select, group=group_select, tstart=t1, tstop=t2, stat=stat_select,
                 plot_warning_low=wL, plot_caution_low=cL, plot_caution_high=cH, 
                 plot_warning_high=wH, remove_bads=filter_bads)

    tabs = Tab(children=[page1, page2, page3])

    tabs.set_title(0, 'MSID, Dates')
    tabs.set_title(1, 'Limits')
    tabs.set_title(2, 'Misc.')

    display(tabs)
Example #12
0
    def _make_add_widget_repr(self, component_slider):
        dropdown_repr_name = Dropdown(options=REPRESENTATION_NAMES, value='cartoon')
        repr_selection = Text(value='*', description='')
        repr_button = Button(description='Add', tooltip="""Add representation.
        You can also hit Enter in selection box""")
        repr_button.layout = Layout(width='auto', flex='1 1 auto')

        dropdown_repr_name.layout.width = repr_selection.layout.width = default.DEFAULT_TEXT_WIDTH

        def on_click_or_submit(button_or_text_area):
            self._view.add_representation(selection=repr_selection.value.strip(),
                    repr_type=dropdown_repr_name.value,
                    component=component_slider.value)

        repr_button.on_click(on_click_or_submit)
        repr_selection.on_submit(on_click_or_submit)
        add_repr_box = HBox([repr_button, dropdown_repr_name, repr_selection])
        add_repr_box._ngl_name = 'add_repr_box'

        return add_repr_box
Example #13
0
def _default_toolbar(figure):
    pz = panzoom(figure.marks)
    normal_btn = ToggleButton(icon='fa-circle-o', tooltip='Normal', value=True)
    pz_btn = ToggleButton(icon='fa-arrows', tooltip='Pan and Zoom', value=False)
    snapshot_btn = Button(icon='fa-thumb-tack', tooltip='Snapshot View')
    reset_btn = Button(icon='fa-refresh', tooltip='Reset View')
    save_btn = Button(icon='fa-save', tooltip='Save as .png Image')

    def tog(btn, *args):
        # Traitlets closure
        def cb():
            for other in args:
                other.value = not btn.value
        return cb

    def overl(btn, value):
        # Traitlets closure
        def cb():
            if btn.value:
                figure.interaction = value
        return cb

    def snapshot(_):
        pz.snapshot()

    def reset(_):
        pz.reset()

    def save(_):
        figure.save()

    pz_btn.on_trait_change(tog(pz_btn, normal_btn))
    pz_btn.on_trait_change(overl(pz_btn, pz))

    normal_btn.on_trait_change(tog(normal_btn, pz_btn))
    normal_btn.on_trait_change(overl(normal_btn, None))

    snapshot_btn.on_click(snapshot)
    reset_btn.on_click(reset)
    save_btn.on_click(save)
    figure.interaction = None

    button_group = HBox([normal_btn, pz_btn, snapshot_btn, reset_btn, save_btn])
    button_group._dom_classes = list(button_group._dom_classes) + ['btn-group']
    return button_group
Example #14
0
def show_items_feature_form(table, periods):
    tree = defaultdict(dict)
    for period in periods:
        section = period.section
        tree[section.group][section.name] = period.features

    def update(button, table, feature):
        clear_output()
        plot_items_feature(table, feature)
    
    group_pages = []
    group_titles = []
    for group_title, group in tree.iteritems():
        section_pages = []
        section_titles = []
        for section_title, features in group.iteritems():
            buttons = []
            for feature in features:
                button = Button(description=feature.name)
                button.on_click(partial(
                    update,
                    table=table,
                    feature=feature)
                )
                buttons.append(button)
            section_pages.append(VBox(children=buttons))
            section_titles.append(section_title)
        accordion = Accordion(children=section_pages)
        for index, title in enumerate(section_titles):
            accordion.set_title(index, title)
        group_pages.append(accordion)
        group_titles.append(group_title)
    accordion = Accordion(children=group_pages)
    for index, title in enumerate(group_titles):
        accordion.set_title(index, title)
    return accordion
Example #15
0
    def _init_gui(self):

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

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

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

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

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

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

        return _ListDict([('close', close),
                          ('frame', frame),
                          ('cols', cfol),
                          ('rows', rfol)])
 def _init_ui(self) -> VBox:
     "Initialize the widget UI and return the UI."
     self._search_input = Text(placeholder="What images to search for?")
     self._count_input = BoundedIntText(placeholder="How many pics?", value=10, min=1, max=5000, step=1,
                                        layout=Layout(width='60px'))
     self._size_input = Dropdown(options= _img_sizes.keys(), value='>400*300', layout=Layout(width='120px'))
     self._download_button = Button(description="Search & Download", icon="download", layout=Layout(width='200px'))
     self._download_button.on_click(self.on_download_button_click)
     self._output = Output()
     self._controls_pane  = HBox([self._search_input, self._count_input, self._size_input, self._download_button],
                                 layout=Layout(width='auto', height='40px'))
     self._heading = ""
     self._download_complete_heading = "<h3>Download complete. Here are a few images</h3>"
     self._preview_header = widgets.HTML(self._heading, layout=Layout(height='60px'))
     self._img_pane = Box(layout=Layout(display='inline'))
     return VBox([self._controls_pane, self._preview_header, self._img_pane])
 def __init__(self,fdpi=300,fsize=(4,3),flabel="fig") :
     # Set local variables
     self.fdpi=fdpi
     self.fsize=fsize
     self.flabel=flabel
     
     # Generate figure
     self.fig = figure(dpi=self.fdpi,figsize=self.fsize)
     close(self.fig)
     
     # Generate plot axes for the figure
     self.ax=self.fig.add_subplot(111)
     
     # Create an html widget for the figure picture
     self.outputHTML = HTML()
     
     # Create save figure widget
     self.btn = Button(description = 'Save %s' % flabel)
     self.btn.on_click(self.btnfunc)
Example #18
0
player2Text = Label(value='Movimiento de jugador 2:',
                    layout=Layout(margin='0px 16px 0px 0px'))
player2TextFrom = Text(
    placeholder='Desde (ej: -4,5)',
    disabled=False,
    layout=Layout(max_width='128px', margin='0px 16px 0px 0px')
)
player2TextTo = Text(
    placeholder='Hacia (ej: -3,4)',
    style={'description_width': 'initial'},
    disabled=False,
    layout=Layout(max_width='128px', margin='0px 16px 0px 0px')
)
player2Button = Button(
    description='Mover',
    disabled=False,
    button_style='warning', # 'success', 'info', 'warning', 'danger' or ''
    layout=Layout(max_width='80px', margin='0px 16px 0px 0px')
)
player2TextError = Label(value='')
box2_layout = Layout(display='flex',
                    flex_flow='row',
                    margin='8px 0px 8px 0px',
                    width='100%')
box2 = Box(children=[player2Text, player2TextFrom, player2TextTo, player2Button, player2TextError], layout=box2_layout)

# Todo
main_box_layout = Layout(display='flex',
                        flex_flow='column',
                        width='100%')
main_box = Box(children=[box2], layout=main_box_layout)
Example #19
0
 def __get_widgets(self, chromosomes, browser, frame=None):
     if frame is None:
         frame = HTML()
     tracks = self.__get_tracks_name(browser)
     return OrderedDict(
         [
             ("chromosomes_list", Dropdown(options=chromosomes)),
             ("left_button", Button(icon="arrow-left")),
             ("right_button", Button(icon="arrow-right")),
             ("zoom_out_button", Button(icon="search-minus")),
             ("zoom_in_button", Button(icon="search-plus")),
             (
                 "range_textbox",
                 Text(placeholder="genome range like: 'chr1:10000-20000'"),
             ),
             ("go_button", Button(description="Go")),
             (
                 "range_slider",
                 IntRangeSlider(
                     continuous_update=False,
                     readout=False,
                     layout=Layout(width='90%'),
                 ),
             ),
             ("range_min_label", Label("", layout=Layout(width='2%'))),
             ("range_max_label", Label("", layout=Layout(width='20%'))),
             (
                 "auto_check_box",
                 Checkbox(
                     value=True,
                     description="Auto Range",
                     layout=Layout(width='120px'),
                     style={'description_width': 'initial'},
                 ),
             ),
             (
                 "track_min_val_float_text",
                 FloatText(
                     value=0.0001,
                     description="Track's min value:",
                     step=0.5,
                     disabled=True,
                     layout=Layout(width='30%'),
                     style={'description_width': 'initial'},
                 ),
             ),
             (
                 "track_max_val_float_text",
                 FloatText(
                     value=10,
                     description="Track's max value:",
                     step=0.5,
                     disabled=True,
                     layout=Layout(width='30%'),
                     style={'description_width': 'initial'},
                 ),
             ),
             (
                 "track_dropdown",
                 Dropdown(
                     options=[ALL_BW_MARK] + tracks,
                     value=ALL_BW_MARK,
                     description="Select track",
                     disabled=True,
                 ),
             ),
             ("frame", frame),
         ]
     )
    def __init__(self):
        # Stores the respective line number and variable changes for each
        # exection step
        self._tracer = TimeTravelTracer()
        self._current_state = None
        self._debugger = None

        self._code_output = HTML()
        self._var_output = Output()
        self._watchpoint_output = Output()
        self._breakpoint_output = Output()

        self._diff_slider = IntSlider(
            min=1,
            readout=False,
            layout=Layout(width="99%"),
            tooltip="Execution timeline",
        )
        self._diff_slider.observe(self._handle_diff_slider, names="value")

        self._autoplay = Play(
            tooltip="Automatic playback of the execution",
            layout=Layout(height="30px"),
        )
        self._auto_link = jsdlink((self._autoplay, "value"),
                                  (self._diff_slider, "value"))

        self._speed_slider = IntSlider(description="Delay (ms)",
                                       min=100,
                                       max=1000,
                                       step=100,
                                       value=500)
        self._speed_link = jsdlink((self._speed_slider, "value"),
                                   (self._autoplay, "interval"))

        self._reverse_autoplay = ToggleButton(
            value=False,
            icon="history",
            tooltip="Reverse autoplay",
            layout=Layout(width="40px"),
        )
        self._reverse_autoplay.observe(self._handle_reverse_button)

        self._watchpoint_input = Text(
            layout=Layout(width="150px"),
            placeholder="Watch expression",
        )
        self._add_watchpoint = Button(
            icon="plus",
            tooltip="Add an expression or variable to watch",
            layout=Layout(width="50px"),
        )
        self._add_watchpoint.on_click(self.watch_command)

        self._watchpoint_dropdown = Dropdown(layout=Layout(width="150px"), )
        self._remove_watchpoint = Button(
            icon="trash",
            tooltip="Remove a watchpoint",
            layout=Layout(width="50px"),
        )
        self._remove_watchpoint.on_click(self.unwatch_command)

        self._breakpoint_layout = GridspecLayout(3, 1)

        self._add_breakpoint = Button(
            icon="plus",
            tooltip="Add a breakpoint",
            name="breakpoint_button",
            layout=Layout(width="40px"),
        )
        self._add_breakpoint.on_click(self._handle_breakpoint)

        self._disable_breakpoint_button = Button(
            icon="eye-slash",
            tooltip="Disable breakpoint",
            layout=Layout(width="50px"),
        )
        self._disable_breakpoint_button.on_click(self.disable_command)

        self._remove_breakpoint_button = Button(
            icon="trash",
            tooltip="Remove breakpoint",
            layout=Layout(width="50px"),
        )
        self._remove_breakpoint_button.on_click(self.delete_command)

        self._breakpoint_dropdown = Dropdown(layout=Layout(width="70px"))

        self._function_dropdown = Dropdown(layout=Layout(width="200px"))
        self._function_dropdown.disabled = True
        self._breakpoint_type = Dropdown(
            options=["Line", "Function", "Conditional"],
            value="Line",
            layout=Layout(width="100px"),
        )

        self._breakpoint_type.observe(self._handle_breakpoint_type,
                                      names="value")

        self._condition_input = Text(placeholder="Enter condition",
                                     layout=Layout(width="200px"))
        self._condition_input.disabled = True

        self._line_input = Text(
            placeholder="Line Number",
            name="line_input",
            layout=Layout(width="100px"),
        )

        self._breakpoint_layout = VBox([
            HBox([
                self._add_breakpoint,
                self._breakpoint_type,
                self._function_dropdown,
                self._line_input,
                self._condition_input,
                self._breakpoint_dropdown,
                self._remove_breakpoint_button,
                self._disable_breakpoint_button,
            ]),
            self._breakpoint_output,
        ])

        self._search_input = Text(placeholder="Search...")
        self._search_input.observe(self._handle_search_input, names="value")

        self._search_results = Output()
        self._search_layout = VBox([
            self._search_input,
            self._search_results,
        ])

        # Remove shadows from scrolling
        style = """
            <style>
               .jupyter-widgets-output-area .output_scroll {
                    border-radius: unset !important;
                    -webkit-box-shadow: unset !important;
                    box-shadow: unset !important;
                }
            </style>
            """
        display(HTML(style))

        for key, item in self._BUTTONS.items():
            self.register_button(key, **item)

        self._code_layout = GridspecLayout(4, 4, grid_gap="20px")

        self._code_layout[0:4, 0:3] = HBox(
            [self._code_output],
            layout=Layout(height="500px",
                          overflow_y="scroll",
                          border="2px solid black"),
        )
        self._code_layout[0:2, 3] = self._var_output
        self._code_layout[2:4, 3] = VBox([
            HBox([self._add_watchpoint, self._watchpoint_input]),
            HBox([self._remove_watchpoint, self._watchpoint_dropdown]),
            self._watchpoint_output,
        ])

        self._code_nav_layout = VBox([
            HBox([
                *self.get_buttons(),
                self._autoplay,
                self._reverse_autoplay,
                self._speed_slider,
            ]),
            self._diff_slider,
            self._code_layout,
        ])

        self._main_layout = Tab(
            [
                self._code_nav_layout,
                self._breakpoint_layout,
                self._search_layout,
            ],
            layout=Layout(height="650px"),
        )

        self._main_layout.set_title(0, "Code")
        self._main_layout.set_title(1, "Breakpoints")
        self._main_layout.set_title(2, "Search")

        display(self._main_layout)
 def register_button(self, key, **kwargs):
     button = Button(description="", layout=Layout(width="40px"), **kwargs)
     func = getattr(self, key + "_command")
     button.on_click(func)
     self._BUTTONS[key]["button"] = button
Example #22
0
class FileChooser(VBox):

    _LBL_TEMPLATE = '<span style="margin-left:10px; color:{1};">{0}</span>'
    _LBL_NOFILE = 'No file selected'

    def __init__(self,
                 path=os.getcwd(),
                 filename='',
                 title='',
                 select_desc='Select',
                 change_desc='Change',
                 show_hidden=False,
                 directory=False,
                 **kwargs):

        self._select_desc = select_desc
        self._default_path = path
        self._show_hidden = show_hidden
        self._select_desc = select_desc
        self._change_desc = change_desc
        self._path = path

        self._updir = Button(description='Up Directory')

        self._dircontent = Select(rows=8,
                                  layout=Layout(width='auto',
                                                grid_area='dircontent'))
        self._cancel = Button(description='Cancel',
                              layout=Layout(width='auto', display='none'))
        self._select = Button(description=self._select_desc,
                              layout=Layout(width='auto'))

        self._label = HTML(value=self._LBL_TEMPLATE.format(
            self._LBL_NOFILE, 'black'),
                           placeholder='',
                           description='')

        self._title = HTML(value=title)

        if title is '':
            self._title.layout.display = 'none'

        self._updir.on_click(self._on_updir_click)
        self._select.on_click(self._on_select_click)
        self._cancel.on_click(self._on_cancel_click)

        # Layout
        self._gb = GridBox(children=[self._updir, self._dircontent],
                           layout=Layout(display='none',
                                         width='500px',
                                         grid_gap='0px 0px',
                                         grid_template_rows='auto auto',
                                         grid_template_columns='60% 40%',
                                         grid_template_areas='''
					'pathlist filename'
					'dircontent dircontent'
					'''))

        self._dircontent.observe(self._on_dircontent_select, names='value')

        buttonbar = HBox(children=[
            self._select,
            self._cancel,
            self._label,
        ],
                         layout=Layout(width='auto'))

        # Call setter to set initial form values
        self._set_form_values(self._path)

        # Call VBox super class __init__
        super().__init__(children=[
            self._gb,
            buttonbar,
        ],
                         layout=Layout(width='auto'),
                         **kwargs)

    def _set_form_values(self, path):
        # Disable triggers to prevent selecting an entry in the Select
        # box from automatically triggering a new event.
        self._dircontent.unobserve(self._on_dircontent_select, names='value')

        self._dircontent.options = get_dir_contents(path,
                                                    hidden=self._show_hidden)
        self._dircontent.value = None

        # Reenable triggers again
        self._dircontent.observe(self._on_dircontent_select, names='value')

    def _on_dircontent_select(self, change):
        '''Handler for when a folder entry is selected'''
        new_path = update_path(self._path, change['new'])

        # Check if folder or file
        if os.path.isdir(new_path):
            self._path = new_path
        #elif os.path.isfile(new_path):
        #	path = self._path

        self._set_form_values(self._path)

    def _on_updir_click(self, b):
        self._path = os.path.split(self._path)[0]
        self._set_form_values(self._path)

    def _on_cancel_click(self, b):
        self._gb.layout.display = 'none'

    def _on_select_click(self, b):
        '''Handler for when the select button is clicked'''
        if self._gb.layout.display is 'none':
            self._gb.layout.display = None
            self._cancel.layout.display = None

            path = self._default_path
            self._set_form_values(path)

        else:
            self._gb.layout.display = 'none'
            self._cancel.layout.display = 'none'
            self._select.description = self._change_desc
            #self._selected_filename = self._filename.value
            # self._default_path = self._selected_path
            # self._default_filename = self._selected_filename

            selected_path = self._path
            #if( os.path.isdir( selected_path ) ):
            #	self._path = selected_path

            pathOK = check_plate_path(self._path)
            color = 'red'
            if (pathOK): color = 'green'
            self._label.value = self._LBL_TEMPLATE.format(selected_path, color)
            self._set_form_values(self._path)
Example #23
0
######### Interactive ##########
################################

def interactive_plot(f):
    interact = interactive(f, M = M, 
                               bpref = bpref, 
                               dpref = dpref, 
                               rc = rc,
                               rho00 = rho00,
                               gpref = gpref,
                               continuous_update=False)
    return interact

################################
########### Button #############
################################

button = Button(
    description="Best Fit",
    button_style='warning', # 'success', 'info', 'warning', 'danger' or ''
    icon='check')
out = Output()

def on_button_clicked(_):
    M.value = best_M
    bpref.value = best_bpref
    dpref.value = best_dpref
    rho00.value = best_rho00
    gpref.value = best_gpref

button.on_click(on_button_clicked)
Example #24
0
    def __init__(self,
                 position: str = "bottomleft",
                 attr_name: str = "style",
                 kind: str = "stroke",
                 orientation: str = "horizontal",
                 transparent: bool = False,
                 a_map: Map = None,
                 layer: Layer = None,
                 place_control: bool = True):
        """Add a widget to the map that allows styling some given layer.

        At the moment only the stroke color, opacity and weight can be changed
        using a color picker and sliders. Dash array might follow later.

        :param m: The map object to which to add a styling widget.
        :param layer: The layer object which is to be styled.
        :param attr_name: The layer's attribute name storing the style object.
            This is usually one of: "style", "hover_style", and "point_style"
        :param kind: The kind of style, either "stroke" or "fill".
        :param orientation: The orientation of the UI elements, either "horizontal"
            (default) or "vertical".
        :param transparent: A flag to indicate if the widget background should be
            transparent (default: ``False``). 
        :param position: The map corner where this widget will be placed. 

        TODO: The UI elements should reflect changes to the layer triggered by
              others. 
        """
        assert kind in ["stroke", "fill"]
        assert orientation in ["horizontal", "vertical"]

        def restyle(change):
            if change["type"] != "change":
                return
            owner = change["owner"]
            style_copy = copy.copy(getattr(layer, attr_name))
            attr_map = {
                p: "color" if kind == "stroke" else "fillColor",
                o: "opacity" if kind == "stroke" else "fillOpacity",
                w: "weight"
            }
            if owner in [p, o, w]:
                style_copy[attr_map[owner]] = owner.value
                setattr(layer, attr_name, style_copy)

        def close(button):
            a_map.remove_control(wc)

        attr = getattr(layer, attr_name)
        style = getattr(layer, "style")

        b = ToggleButton(description="Stroke",
                         value=True,
                         tooltip="Stroke or not?")
        dummy = ToggleButton(value=not b.value)
        b.layout.width = "80px"

        name = "color" if kind == "stroke" else "fillColor"
        p = ColorPicker(value=attr.get(name, style.get(name, "#3885ff")))
        p.layout.width = "100px"

        name = "opacity" if kind == "stroke" else "fillOpacity"
        o = FloatSlider(min=0,
                        max=1,
                        value=attr.get(name, style.get(name, 0.5)))
        o.layout.width = "200px"

        w = IntSlider(min=0,
                      max=50,
                      value=attr.get("weight", style.get("weight", 5)))
        w.layout.width = "200px"

        layout = Layout(width="28px", height="28px", padding="0px 0px 0px 4px")
        q = Button(tooltip="Close",
                   icon="close",
                   button_style="info",
                   layout=layout)

        for el in [p, o, w] if kind == "stroke" else [p, o]:
            link((dummy, "value"), (el, "disabled"))

        p.observe(restyle)
        o.observe(restyle)
        if kind == "stroke":
            w.observe(restyle)
        else:
            w.disabled = True
        q.on_click(close)

        desc = HTML(f"{kind} {attr_name}")

        if orientation == "horizontal":
            self.widget = HBox([desc, p, w, o, q])
        elif orientation == "vertical":
            self.widget = VBox([HBox([desc, q]), p, w, o])

        wc = WidgetControl(widget=self.widget,
                           position=position,
                           transparent_bg=transparent)
        a_map.add_control(wc)
Example #25
0
    def _make_reference_widget(self):
        def make_func():
            parameters = self._view._full_stage_parameters

            def func(pan_speed=parameters.get('panSpeed', 0.8),
                     rotate_speed=parameters.get('rotateSpeed', 2),
                     zoom_speed=parameters.get('zoomSpeed', 1.2),
                     clip_dist=parameters.get('clipDist', 10),
                     camera_fov=parameters.get('cameraFov', 40),
                     clip_far=parameters.get('clipFar', 100),
                     clip_near=parameters.get('clipNear', 0),
                     fog_far=parameters.get('fogFar', 100),
                     fog_near=parameters.get('fogNear', 50),
                     impostor=parameters.get('impostor', True),
                     light_intensity=parameters.get('lightIntensity', 1),
                     quality=parameters.get('quality', 'medium'),
                     sample_level=parameters.get('sampleLevel', 1)):

                self._view.parameters = dict(panSpeed=pan_speed,
                                             rotateSpeed=rotate_speed,
                                             zoomSpeed=zoom_speed,
                                             clipDist=clip_dist,
                                             clipFar=clip_far,
                                             clipNear=clip_near,
                                             cameraFov=camera_fov,
                                             fogFar=fog_far,
                                             fogNear=fog_near,
                                             impostor=impostor,
                                             lightIntensity=light_intensity,
                                             quality=quality,
                                             sampleLevel=sample_level)

            return func

        def make_widget_box():
            widget_sliders = interactive(make_func(),
                                         pan_speed=(0, 10, 0.1),
                                         rotate_speed=(0, 10, 1),
                                         zoom_speed=(0, 10, 1),
                                         clip_dist=(0, 200, 5),
                                         clip_far=(0, 100, 1),
                                         clip_near=(0, 100, 1),
                                         camera_fov=(15, 120, 1),
                                         fog_far=(0, 100, 1),
                                         fog_near=(0, 100, 1),
                                         light_intensity=(0, 10, 0.02),
                                         quality=['low', 'medium', 'high'],
                                         sample_level=(-1, 5, 1))

            for child in widget_sliders.children:
                if isinstance(child, (IntSlider, FloatSlider)):
                    child.width = DEFAULT_SLIDER_WIDTH
            return widget_sliders

        widget_sliders = make_widget_box()
        reset_button = Button(description='Reset')
        widget_sliders.children = [
            reset_button,
        ] + list(widget_sliders.children)

        def on_click(reset_button):
            self._view.parameters = self._view._original_stage_parameters
            self._view._full_stage_parameters = self._view._original_stage_parameters
            widget_sliders.children = [
                reset_button,
            ] + list(make_widget_box().children)

        reset_button.on_click(on_click)

        return widget_sliders
Example #26
0
class Interface():
    def __init__(self,figsize=(6,6)):
        self.figsize=figsize
        self.size_slider=IntSlider(description='Grid Size',min=4,max=50)
        display(self.size_slider)

        self.nb_ob_slider=IntSlider(description='Obstacles',min=0,max=7)
        display(self.nb_ob_slider)

        self.gen_inst_button=Button(description='Generate Instance',margin=10)
        self.gen_pos_button=Button(description='Generate Start/End Positions',margin=10)
        self.gen_path_button=Button(description='Generate Path',margin=10)
        self.inst_but_container=HBox(children=[self.gen_inst_button,self.gen_pos_button,self.gen_path_button])
        self.inst_but_container.width = '100%'
        display(self.inst_but_container)


        self.show_path_button=Latex(value='Path: Value:  Actions:',margin=10)
        display(self.show_path_button)

        self.size_slider.on_trait_change(self._on_size_slider_change,'value')
        self.gen_inst_button.on_click(self._on_gen_inst_button_click)
        self.gen_pos_button.on_click(self._on_pos_button_click)
        self.gen_path_button.on_click(self._on_gen_path_button_click)
        
        self.gen_path_button.disabled=True
        self.gen_pos_button.disabled=True
            
        plt.close()
        plt.axis('off')
        self.fig=plt.figure(figsize=self.figsize)
        self.ax=self.fig.add_subplot(111)
        

    def _on_size_slider_change(self,name,value):
        self.nb_ob_slider.max=int(value)**2/2-4 #Constrain on number of obstacles
    
    def _on_gen_inst_button_click(self,b):
        self.gen_path_button.disabled=True
        self.gen_pos_button.disabled=False
            
        self.show_path_button.value='Path: Value:  Actions:'

        for line in self.ax.lines:
            line.set_visible(False)
            del(line)
        #Instance Generation
        self.M=self.size_slider.value
        self.nb_ob=self.nb_ob_slider.value
        
        self.A=gen_rand_instance(self.M,self.M,self.nb_ob)
        
        self.G=gen_graph(self.A)
               
        
        if hasattr(self, 'ax'):
        #    print self.ax
            self.ax.cla()
        if hasattr(self, 'start_circle'):
            del(self.start_circle)
            del(self.end_circle)
            del(self.arrow)


        
        colors=['white','grey']
        self.ax.set_ylim([0,self.A.shape[0]])
        self.ax.set_xlim([0,self.A.shape[1]])
        self.ax.set_axis_off()
        self.tb = Table(self.ax, bbox=[0,0,1,1])
        nrows, ncols = self.A.shape
        width, height = 1.0 / ncols, 1.0 / nrows
        # Add cells
        for (i,j),val in np.ndenumerate(self.A):
            color=colors[val]
            self.tb.add_cell(i, j, width, height,loc='center', facecolor=color)
        # Row Labels...
        for i in range(self.A.shape[0]):
            self.tb.add_cell(i, -1, width, height, text=i, loc='right', 
                        edgecolor='none', facecolor='none')
        # Column Labels
        for j in range(self.A.shape[1]):
            self.tb.add_cell(-1, j, width, height/2, text=j, loc='center', 
                               edgecolor='none', facecolor='none')
        self.ax.add_table(self.tb)
        self.ax.invert_yaxis()
        #self.leg=self.ax.legend(bbox_to_anchor=(1.3, 1.05),fancybox=True)
        #self.leg.get_frame().set_alpha(0.5)
        #self.ax.legend()
        plt.show()

        
    def _on_pos_button_click(self,b):
        for line in self.ax.lines:
            line.set_visible(False)
            del(line)
        self.gen_path_button.disabled=False

        self.start,self.end=gen_rand_positions(self.G)
        #Ajout Depart
        start_inst=self.start[:2][::-1]
        #Ajout Direction de Depart
        start_dir=self.start[2]
        start_posA=start_inst
        end_inst=self.end[:2][::-1]
        if(start_dir==1):        
            start_posB=(start_posA[0],start_posA[1]-1)
        if(start_dir==2):
            start_posB=(start_posA[0]+1,start_posA[1])
        if(start_dir==3):
            start_posB=(start_posA[0],start_posA[1]+1)
        if(start_dir==4):
            start_posB=(start_posA[0]-1,start_posA[1]) 
            
        if hasattr(self, 'start_circle'): #deja trace
            self.start_circle.set_visible(True)
            self.end_circle.set_visible(True)
            self.arrow.set_visible(True)
            self.start_circle.center=start_inst
            self.arrow.set_positions(start_posA,start_posB)
            self.end_circle.center=end_inst
            self.show_path_button.value='Path: Value:  Actions:'
            
        else: #jamais trace encore
            #Position de Depart
            self.start_circle=Circle(start_inst,radius=0.5,alpha=0.8, color='g',zorder=2,label='Depart',clip_on=False)
            self.ax.add_patch(self.start_circle)
            #Direction de Depart
            self.arrow=FancyArrowPatch(start_posA,start_posB,arrowstyle='->',color='m',mutation_scale=15.0,lw=2,zorder=3,clip_on=False)
            self.ax.add_patch(self.arrow)
            #Ajout Arrivee

            self.end_circle=Circle(end_inst,radius=0.5,alpha=0.8, color='r',zorder=2,label='Arrivee',clip_on=False)
            self.ax.add_patch(self.end_circle)
            self.leg=self.ax.legend(bbox_to_anchor=(1.1, 1.05),fancybox=True)
            self.leg.get_frame().set_alpha(0.5)
        
        plt.show()
        

        
    def _on_gen_path_button_click(self,b):
        self.gen_path_button.disabled=True

        self.result=gen_shortest_path(self.start,self.end,self.G)
        self.show_path_button.value='Path: Value:  '+str(self.result[0])+' Actions: '+' '.join(e for e in self.result[1])    
    
        #Ajout Chemin
        for i,j in self.result[2]:
            self.ax.add_line(lines.Line2D((i[1],j[1]),(i[0],j[0]),linewidth=3,zorder=1,clip_on=False))
        plt.draw()
Example #27
0
    def make_config(self):
        layout = Layout()
        style = {"description_width": "initial"}
        checkbox1 = Checkbox(description="Show Targets", value=self.net.config["show_targets"],
                             layout=layout, style=style)
        checkbox1.observe(lambda change: self.set_attr(self.net.config, "show_targets", change["new"]), names='value')
        checkbox2 = Checkbox(description="Errors", value=self.net.config["show_errors"],
                             layout=layout, style=style)
        checkbox2.observe(lambda change: self.set_attr(self.net.config, "show_errors", change["new"]), names='value')

        hspace = IntText(value=self.net.config["hspace"], description="Horizontal space between banks:",
                         style=style, layout=layout)
        hspace.observe(lambda change: self.set_attr(self.net.config, "hspace", change["new"]), names='value')
        vspace = IntText(value=self.net.config["vspace"], description="Vertical space between layers:",
                         style=style, layout=layout)
        vspace.observe(lambda change: self.set_attr(self.net.config, "vspace", change["new"]), names='value')
        self.feature_bank = Select(description="Details:", value=self.net.config["dashboard.features.bank"],
                              options=[""] + [layer.name for layer in self.net.layers],
                              rows=1)
        self.feature_bank.observe(self.regenerate, names='value')
        self.control_select = Select(
            options=['Test', 'Train'],
            value=self.net.config["dashboard.dataset"],
            description='Dataset:',
            rows=1
        )
        self.control_select.observe(self.change_select, names='value')
        column1 = [self.control_select,
                   self.zoom_slider,
                   hspace,
                   vspace,
                   HBox([checkbox1, checkbox2]),
                   self.feature_bank,
                   self.feature_columns,
                   self.feature_scale
        ]
        ## Make layer selectable, and update-able:
        column2 = []
        layer = self.net.layers[-1]
        self.layer_select = Select(description="Layer:", value=layer.name,
                                   options=[layer.name for layer in
                                            self.net.layers],
                                   rows=1)
        self.layer_select.observe(self.update_layer_selection, names='value')
        column2.append(self.layer_select)
        self.layer_visible_checkbox = Checkbox(description="Visible", value=layer.visible, layout=layout)
        self.layer_visible_checkbox.observe(self.update_layer, names='value')
        column2.append(self.layer_visible_checkbox)
        self.layer_colormap = Select(description="Colormap:",
                                     options=[""] + AVAILABLE_COLORMAPS,
                                     value=layer.colormap if layer.colormap is not None else "", layout=layout, rows=1)
        self.layer_colormap_image = HTML(value="""<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap)))
        self.layer_colormap.observe(self.update_layer, names='value')
        column2.append(self.layer_colormap)
        column2.append(self.layer_colormap_image)
        ## get dynamic minmax; if you change it it will set it in layer as override:
        minmax = layer.get_act_minmax()
        self.layer_mindim = FloatText(description="Leftmost color maps to:", value=minmax[0], style=style)
        self.layer_maxdim = FloatText(description="Rightmost color maps to:", value=minmax[1], style=style)
        self.layer_mindim.observe(self.update_layer, names='value')
        self.layer_maxdim.observe(self.update_layer, names='value')
        column2.append(self.layer_mindim)
        column2.append(self.layer_maxdim)
        output_shape = layer.get_output_shape()
        self.layer_feature = IntText(value=layer.feature, description="Feature to show:", style=style)
        self.svg_rotate = Checkbox(description="Rotate", value=layer.visible, layout=layout)
        self.layer_feature.observe(self.update_layer, names='value')
        column2.append(self.layer_feature)
        self.svg_rotate = Checkbox(description="Rotate network",
                                   value=self.net.config["svg_rotate"],
                                   style={"description_width": 'initial'},
                                   layout=Layout(width="52%"))
        self.svg_rotate.observe(lambda change: self.set_attr(self.net.config, "svg_rotate", change["new"]), names='value')
        self.save_config_button = Button(icon="save", layout=Layout(width="10%"))
        self.save_config_button.on_click(self.save_config)
        column2.append(HBox([self.svg_rotate, self.save_config_button]))
        config_children = HBox([VBox(column1, layout=Layout(width="100%")),
                                VBox(column2, layout=Layout(width="100%"))])
        accordion = Accordion(children=[config_children])
        accordion.set_title(0, self.net.name)
        accordion.selected_index = None
        return accordion
Example #28
0
    def interactive_graph(self, data_types=('expression', 'splicing'),
                          sample_subsets=None,
                          feature_subsets=None,
                          featurewise=False,
                          cov_std_cut=(0.1, 3),
                          degree_cut=(0, 10),
                          n_pcs=(2, 100),
                          draw_labels=False,
                          feature_of_interest="RBFOX2",
                          weight_fun=None,
                          use_pc_1=True, use_pc_2=True, use_pc_3=True,
                          use_pc_4=True,
                          savefile='figures/last.graph.pdf'):

        from IPython.html.widgets import interact

        # not sure why nested fxns are required for this, but they are... i
        # think...
        def do_interact(data_type='expression',
                        sample_subset=self.default_sample_subsets,
                        feature_subset=self.default_feature_subsets,
                        weight_fun=NetworkerViz.weight_funs,
                        featurewise=False,
                        use_pc_1=True, use_pc_2=True, use_pc_3=True,
                        use_pc_4=True, degree_cut=1,
                        cov_std_cut=1.8, n_pcs=5,
                        feature_of_interest="RBFOX2",
                        draw_labels=False):

            for k, v in locals().iteritems():
                if k == 'self':
                    continue
                sys.stdout.write('{} : {}\n'.format(k, v))

            if data_type == 'expression':
                assert (feature_subset in
                        self.expression.feature_subsets.keys())
            if data_type == 'splicing':
                assert (feature_subset in
                        self.splicing.feature_subsets.keys())

            self.plot_graph(data_type=data_type,
                            sample_subset=sample_subset,
                            feature_subset=feature_subset,
                            featurewise=featurewise, draw_labels=draw_labels,
                            degree_cut=degree_cut, cov_std_cut=cov_std_cut,
                            n_pcs=n_pcs,
                            feature_of_interest=feature_of_interest,
                            use_pc_1=use_pc_1, use_pc_2=use_pc_2,
                            use_pc_3=use_pc_3,
                            use_pc_4=use_pc_4,
                            weight_function=weight_fun)

        if feature_subsets is None:
            feature_subsets = Interactive.get_feature_subsets(self, data_types)

        if sample_subsets is None:
            sample_subsets = self.default_sample_subsets
        if weight_fun is None:
            weight_fun = NetworkerViz.weight_funs

        gui = interact(do_interact,
                       data_type=data_types,
                       sample_subset=sample_subsets,
                       feature_subset=feature_subsets,
                       featurewise=featurewise,
                       cov_std_cut=cov_std_cut,
                       degree_cut=degree_cut,
                       n_pcs=n_pcs,
                       draw_labels=draw_labels,
                       weight_fun=weight_fun,
                       feature_of_interest=feature_of_interest,
                       use_pc_1=use_pc_1, use_pc_2=use_pc_2,
                       use_pc_3=use_pc_3, use_pc_4=use_pc_4)

        def save(w):
            # Make the directory if it's not already there
            filename, extension = os.path.splitext(savefile.value)
            self.maybe_make_directory(savefile.value)
            plt.gcf().savefig(savefile, format=extension.lstrip('.'))

        savefile = Text(description='savefile')
        save_widget = Button(description='save')
        gui.widget.children = list(gui.widget.children) + [savefile,
                                                           save_widget]
        save_widget.on_click(save)

        return gui
Example #29
0
 def _create_widget(self):
     self.addbtn = Button(description='Add')
     self.addbtn.on_click(self.add_row_handler)
     vbox = VBox([self.addbtn])
     vbox.add_class('repeat-innotation')
     return vbox
Example #30
0
    def settings_panel(self):
        # getMolMap calulation settings.  NOTE: should only be called once.
        margin = 2

        num_angles_slider_text = "Number of Inverse Cone Angles to calculate:"
        num_angles_slider_widget = IntSlider(value=1, min=1, max=5)
        num_angles_slider = VBox(
            children=[HTML(value=num_angles_slider_text), num_angles_slider_widget], margin=margin, width="100%"
        )
        link((self.model, "num_angles"), (num_angles_slider_widget, "value"))
        sub_slider_text = "Subdivision value of the icosphere for numerical calculation:"
        sub_slider_widget = IntSlider(value=5, min=1, max=9)
        link((self.model, "sub"), (sub_slider_widget, "value"))
        sub_slider = VBox(children=[HTML(value=sub_slider_text), sub_slider_widget], margin=margin, width="100%")
        #        link((sub_slider, 'value'), (i, 'value'))
        #        print(self.width)
        #        sub_slider.align = 'center'
        #        sub_slider.width = '100%'
        #        sub_slider.border_color = 'black'
        #        sub_slider.border_width = 2

        radius_slider_text = "Cut radius measured from the central atom:"
        radius_slider_widget = FloatSlider(value=0, min=0, max=10)
        link((self.model, "radius"), (radius_slider_widget, "value"))
        radius_slider = VBox(children=[HTML(value=radius_slider_text), radius_slider_widget], margin=margin)

        atomradscale_slider_text = "Atomic radius scaling factor:"
        atomradscale_slider_widget = FloatSlider(value=1, min=0, max=4)
        link((self.model, "rad_scale"), (atomradscale_slider_widget, "value"))
        atomradscale_slider = VBox(
            children=[HTML(value=atomradscale_slider_text), atomradscale_slider_widget], margin=margin
        )

        excludeH_button = Checkbox(description="Exclude H from every geometry:")
        link((self.model, "excludeH"), (excludeH_button, "value"))
        excludeH_button.on_trait_change(self.excludeH_changed, "value")

        dont = "Don't exclude any elements"
        self.dont = dont
        # TODO: Syncronize exclude_list_widget with excludeH button and define an event on the
        # model to filter out the `dont` text.
        # Alternatevily, separate this option into a checkbox and hide the exclude options
        # while the button is selected.
        exclude_list_text = "Exclude elements from every geometry:"
        exclude_list_widget = SelectMultiple(
            options=[dont] + [e.symbol for e in ELEMENTS],
            selected_labels=[dont],
            color="Black",
            font_size=14,
            height=120,
        )
        link((exclude_list_widget, "value"), (self.model, "excludes"))
        # The dirty old SelectMultiple widget does not have an .on_trait_change method.
        # So we create a new traitlet (excludes_notifier), which has an .on_trait_change method
        # because it inherits HasTraits. We link the 'value' trait to excludes_notifier.excludes;
        # and we bind the event handler to excludes_notifier.on_trait_change
        self.excludes_notifier = ExcludesNotifier()
        link((exclude_list_widget, "value"), (self.excludes_notifier, "excludes"))
        self.excludes_notifier.on_trait_change(self.excludes_changed)

        exclude_list = VBox(children=[HTML(value=exclude_list_text), exclude_list_widget], margin=margin)

        atomrad_button = ToggleButtons(
            description="Atomic radius type:",
            options=["vdwrad", "covrad", "atmrad"],
            background_color="AliceBlue",
            margin=margin,
        )
        link((self.model, "rad_type"), (atomrad_button, "value"))
        runbutton = Button(
            description="Run calculation!",
            tooltip="Click here to calculate Buried Volumes and Inverse Cone Angles!",
            margin=margin * 3,
            border_color="#9acfea",
            # border_radius=5,
            border_width=3,
            font_size=20,
        )
        runbutton.on_click(self.run_button_clicked)

        basic_tab = VBox(children=[atomrad_button, excludeH_button])
        sliders = VBox(children=[num_angles_slider, atomradscale_slider, radius_slider, sub_slider])
        sliders.width = "100%"
        sliders.pack = "center"

        advanced_tab = VBox(children=[atomrad_button, sliders, exclude_list])
        main_window = Tab(children=[basic_tab, advanced_tab])
        main_window.set_title(0, "Basic")
        main_window.set_title(1, "Advanced")

        return ControlPanel(
            title="getMolMap Settings:",
            children=[main_window, runbutton],
            border_width=2,
            border_radius=4,
            margin=10,
            padding=0,
        )
Example #31
0
    def __init__(self,
                 path=os.getcwd(),
                 filename='',
                 title='',
                 select_desc='Select',
                 change_desc='Change',
                 show_hidden=False,
                 include_files=True,
                 include_folders=True,
                 **kwargs):

        self._default_path = path  # path.rstrip(os.path.sep)
        self._default_filename = filename
        self._selected_path = ''
        self._selected_filename = ''
        self._show_hidden = show_hidden
        self._select_desc = select_desc
        self._change_desc = change_desc
        self._include_files = include_files
        self._include_folders = include_folders

        if not include_folders and not include_files:
            raise ValueError("You can't exclude both files and folders")

        # Widgets
        self._pathlist = Dropdown(description="",
                                  layout=Layout(width='auto',
                                                grid_area='pathlist'))
        self._filename = Text(
            placeholder='output filename',
            layout=Layout(
                width='auto',
                grid_area='filename',
                visibility='visible' if self._include_files else 'hidden',
            ),
        )
        self._dircontent = Select(rows=8,
                                  layout=Layout(width='auto',
                                                grid_area='dircontent'))
        self._cancel = Button(description='Cancel',
                              layout=Layout(width='auto', display='none'))
        self._select = Button(description=self._select_desc,
                              layout=Layout(width='auto'))

        self._title = HTML(value=title)

        if title is '':
            self._title.layout.display = 'none'

        # Widget observe handlers
        self._pathlist.observe(self._on_pathlist_select, names='value')
        self._dircontent.observe(self._on_dircontent_select, names='value')
        self._filename.observe(self._on_filename_change, names='value')
        self._select.on_click(self._on_select_click)
        self._cancel.on_click(self._on_cancel_click)

        # Selected file label
        self._label = HTML(value=self._LBL_TEMPLATE.format(
            self._LBL_NOFILE if self._include_files else
            self._LBL_NOFOLDER if self._include_folders else "", 'black'),
                           placeholder='',
                           description='')

        # Layout
        self._gb = GridBox(
            children=[self._pathlist, self._filename, self._dircontent],
            layout=Layout(display='none',
                          width='500px',
                          grid_gap='0px 0px',
                          grid_template_rows='auto auto',
                          grid_template_columns='60% 40%',
                          grid_template_areas='''
                    'pathlist filename'
                    'dircontent dircontent'
                    '''))
        buttonbar = HBox(children=[self._select, self._cancel, self._label],
                         layout=Layout(width='auto'))

        # Call setter to set initial form values
        self._set_form_values(self._default_path, self._default_filename)

        # Call VBox super class __init__
        kwargs.setdefault('layout', Layout(width='auto'))
        super().__init__(children=[
            self._title,
            self._gb,
            buttonbar,
        ],
                         **kwargs)
Example #32
0
    def __init__(self):

        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout = {'width': '25%'}
        widget_layout = {'width': '15%'}
        units_button_layout = {'width': '15%'}
        desc_button_layout = {'width': '45%'}

        menv_var1 = Button(description='oxygen (mmHg)',
                           disabled=True,
                           layout=name_button_layout)
        menv_var1.style.button_color = 'tan'

        param_name1 = Button(description='diffusion_coefficient',
                             disabled=True,
                             layout=name_button_layout)

        self.oxygen_diffusion_coefficient = FloatText(value=100000.000000,
                                                      step=10000,
                                                      style=style,
                                                      layout=widget_layout)

        param_name2 = Button(description='decay_rate',
                             disabled=True,
                             layout=name_button_layout)

        self.oxygen_decay_rate = FloatText(value=.1,
                                           step=0.01,
                                           style=style,
                                           layout=widget_layout)
        param_name3 = Button(description='initial_condition',
                             disabled=True,
                             layout=name_button_layout)

        self.oxygen_initial_condition = FloatText(value=38.0,
                                                  style=style,
                                                  layout=widget_layout)
        param_name4 = Button(description='Dirichlet_boundary_condition',
                             disabled=True,
                             layout=name_button_layout)

        self.oxygen_Dirichlet_boundary_condition = FloatText(
            value=38.0, style=style, layout=widget_layout)
        self.oxygen_Dirichlet_boundary_condition_toggle = Checkbox(
            description='on/off',
            disabled=False,
            style=style,
            layout=widget_layout)

        menv_var2 = Button(description='chemoattractant',
                           disabled=True,
                           layout=name_button_layout)
        menv_var2.style.button_color = 'lightgreen'

        param_name5 = Button(description='diffusion_coefficient',
                             disabled=True,
                             layout=name_button_layout)

        self.chemoattractant_diffusion_coefficient = FloatText(
            value=1000, step=100, style=style, layout=widget_layout)

        param_name6 = Button(description='decay_rate',
                             disabled=True,
                             layout=name_button_layout)

        self.chemoattractant_decay_rate = FloatText(value=.1,
                                                    step=0.01,
                                                    style=style,
                                                    layout=widget_layout)
        param_name7 = Button(description='initial_condition',
                             disabled=True,
                             layout=name_button_layout)

        self.chemoattractant_initial_condition = FloatText(
            value=0, style=style, layout=widget_layout)
        param_name8 = Button(description='Dirichlet_boundary_condition',
                             disabled=True,
                             layout=name_button_layout)

        self.chemoattractant_Dirichlet_boundary_condition = FloatText(
            value=0, style=style, layout=widget_layout)
        self.chemoattractant_Dirichlet_boundary_condition_toggle = Checkbox(
            description='on/off',
            disabled=False,
            style=style,
            layout=widget_layout)

        menv_var3 = Button(description='therapeutic',
                           disabled=True,
                           layout=name_button_layout)
        menv_var3.style.button_color = 'tan'

        param_name9 = Button(description='diffusion_coefficient',
                             disabled=True,
                             layout=name_button_layout)

        self.therapeutic_diffusion_coefficient = FloatText(
            value=1000, step=100, style=style, layout=widget_layout)

        param_name10 = Button(description='decay_rate',
                              disabled=True,
                              layout=name_button_layout)

        self.therapeutic_decay_rate = FloatText(value=.15625,
                                                step=0.01,
                                                style=style,
                                                layout=widget_layout)
        param_name11 = Button(description='initial_condition',
                              disabled=True,
                              layout=name_button_layout)

        self.therapeutic_initial_condition = FloatText(value=0,
                                                       style=style,
                                                       layout=widget_layout)
        param_name12 = Button(description='Dirichlet_boundary_condition',
                              disabled=True,
                              layout=name_button_layout)

        self.therapeutic_Dirichlet_boundary_condition = FloatText(
            value=0, style=style, layout=widget_layout)
        self.therapeutic_Dirichlet_boundary_condition_toggle = Checkbox(
            description='on/off',
            disabled=False,
            style=style,
            layout=widget_layout)
        self.calculate_gradient = Checkbox(description='calculate_gradients',
                                           disabled=False,
                                           layout=desc_button_layout)
        self.track_internal = Checkbox(description='track_in_agents',
                                       disabled=False,
                                       layout=desc_button_layout)

        #  ------- micronenv info
        menv_units_button1 = Button(description='micron^2/min',
                                    disabled=True,
                                    layout=units_button_layout)
        menv_units_button2 = Button(description='1/min',
                                    disabled=True,
                                    layout=units_button_layout)
        menv_units_button3 = Button(description='mmHg',
                                    disabled=True,
                                    layout=units_button_layout)
        menv_units_button4 = Button(description='mmHg',
                                    disabled=True,
                                    layout=units_button_layout)
        menv_units_button5 = Button(description='micron^2/min',
                                    disabled=True,
                                    layout=units_button_layout)
        menv_units_button6 = Button(description='1/min',
                                    disabled=True,
                                    layout=units_button_layout)
        units_button1 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button2 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        menv_units_button9 = Button(description='micron^2/min',
                                    disabled=True,
                                    layout=units_button_layout)
        menv_units_button10 = Button(description='1/min',
                                     disabled=True,
                                     layout=units_button_layout)
        units_button3 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button4 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)

        row_oxygen = [
            menv_var1,
        ]
        row1 = [
            param_name1, self.oxygen_diffusion_coefficient, menv_units_button1
        ]
        row2 = [param_name2, self.oxygen_decay_rate, menv_units_button2]
        row3 = [param_name3, self.oxygen_initial_condition, menv_units_button3]
        row4 = [
            param_name4, self.oxygen_Dirichlet_boundary_condition,
            menv_units_button4, self.oxygen_Dirichlet_boundary_condition_toggle
        ]
        row_chemoattractant = [
            menv_var2,
        ]
        row5 = [
            param_name5, self.chemoattractant_diffusion_coefficient,
            menv_units_button5
        ]
        row6 = [
            param_name6, self.chemoattractant_decay_rate, menv_units_button6
        ]
        row7 = [
            param_name7, self.chemoattractant_initial_condition, units_button1
        ]
        row8 = [
            param_name8, self.chemoattractant_Dirichlet_boundary_condition,
            units_button2,
            self.chemoattractant_Dirichlet_boundary_condition_toggle
        ]
        row_therapeutic = [
            menv_var3,
        ]
        row9 = [
            param_name9, self.therapeutic_diffusion_coefficient,
            menv_units_button9
        ]
        row10 = [
            param_name10, self.therapeutic_decay_rate, menv_units_button10
        ]
        row11 = [
            param_name11, self.therapeutic_initial_condition, units_button3
        ]
        row12 = [
            param_name12, self.therapeutic_Dirichlet_boundary_condition,
            units_button4, self.therapeutic_Dirichlet_boundary_condition_toggle
        ]
        row13 = [
            self.calculate_gradient,
        ]
        row14 = [
            self.track_internal,
        ]

        box_layout = Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            width='100%')
        box_oxygen = Box(children=row_oxygen, layout=box_layout)
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box_chemoattractant = Box(children=row_chemoattractant,
                                  layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)
        box6 = Box(children=row6, layout=box_layout)
        box7 = Box(children=row7, layout=box_layout)
        box8 = Box(children=row8, layout=box_layout)
        box_therapeutic = Box(children=row_therapeutic, layout=box_layout)
        box9 = Box(children=row9, layout=box_layout)
        box10 = Box(children=row10, layout=box_layout)
        box11 = Box(children=row11, layout=box_layout)
        box12 = Box(children=row12, layout=box_layout)
        box13 = Box(children=row13, layout=box_layout)
        box14 = Box(children=row14, layout=box_layout)

        self.tab = VBox([
            box_oxygen,
            box1,
            box2,
            box3,
            box4,
            box_chemoattractant,
            box5,
            box6,
            box7,
            box8,
            box_therapeutic,
            box9,
            box10,
            box11,
            box12,
            box13,
            box14,
        ])
Example #33
0
class FileChooser(VBox):

    _LBL_TEMPLATE = '<span style="margin-left:10px; color:{1};">{0}</span>'
    _LBL_NOFILE = 'No file selected'
    _LBL_NOFOLDER = 'No folder selected'

    def __init__(self,
                 path=os.getcwd(),
                 filename='',
                 title='',
                 select_desc='Select',
                 change_desc='Change',
                 show_hidden=False,
                 include_files=True,
                 include_folders=True,
                 **kwargs):

        self._default_path = path  # path.rstrip(os.path.sep)
        self._default_filename = filename
        self._selected_path = ''
        self._selected_filename = ''
        self._show_hidden = show_hidden
        self._select_desc = select_desc
        self._change_desc = change_desc
        self._include_files = include_files
        self._include_folders = include_folders

        if not include_folders and not include_files:
            raise ValueError("You can't exclude both files and folders")

        # Widgets
        self._pathlist = Dropdown(description="",
                                  layout=Layout(width='auto',
                                                grid_area='pathlist'))
        self._filename = Text(
            placeholder='output filename',
            layout=Layout(
                width='auto',
                grid_area='filename',
                visibility='visible' if self._include_files else 'hidden',
            ),
        )
        self._dircontent = Select(rows=8,
                                  layout=Layout(width='auto',
                                                grid_area='dircontent'))
        self._cancel = Button(description='Cancel',
                              layout=Layout(width='auto', display='none'))
        self._select = Button(description=self._select_desc,
                              layout=Layout(width='auto'))

        self._title = HTML(value=title)

        if title is '':
            self._title.layout.display = 'none'

        # Widget observe handlers
        self._pathlist.observe(self._on_pathlist_select, names='value')
        self._dircontent.observe(self._on_dircontent_select, names='value')
        self._filename.observe(self._on_filename_change, names='value')
        self._select.on_click(self._on_select_click)
        self._cancel.on_click(self._on_cancel_click)

        # Selected file label
        self._label = HTML(value=self._LBL_TEMPLATE.format(
            self._LBL_NOFILE if self._include_files else
            self._LBL_NOFOLDER if self._include_folders else "", 'black'),
                           placeholder='',
                           description='')

        # Layout
        self._gb = GridBox(
            children=[self._pathlist, self._filename, self._dircontent],
            layout=Layout(display='none',
                          width='500px',
                          grid_gap='0px 0px',
                          grid_template_rows='auto auto',
                          grid_template_columns='60% 40%',
                          grid_template_areas='''
                    'pathlist filename'
                    'dircontent dircontent'
                    '''))
        buttonbar = HBox(children=[self._select, self._cancel, self._label],
                         layout=Layout(width='auto'))

        # Call setter to set initial form values
        self._set_form_values(self._default_path, self._default_filename)

        # Call VBox super class __init__
        kwargs.setdefault('layout', Layout(width='auto'))
        super().__init__(children=[
            self._title,
            self._gb,
            buttonbar,
        ],
                         **kwargs)

    def _set_form_values(self, path, filename):
        """Set the form values"""

        # Disable triggers to prevent selecting an entry in the Select
        # box from automatically triggering a new event.
        self._pathlist.unobserve(self._on_pathlist_select, names='value')
        self._dircontent.unobserve(self._on_dircontent_select, names='value')
        self._filename.unobserve(self._on_filename_change, names='value')

        # Set form values
        self._pathlist.options = get_subpaths(path)
        self._pathlist.value = path
        self._filename.value = filename
        self._dircontent.options = get_dir_contents(
            path,
            hidden=self._show_hidden,
            include_files=self._include_files,
            include_folders=self._include_folders)

        # If the value in the filename Text box equals a value in the
        # Select box and the entry is a file then select the entry.
        if ((filename in self._dircontent.options)
                and os.path.isfile(os.path.join(path, filename))):
            self._dircontent.value = filename
        else:
            self._dircontent.value = None

        # Reenable triggers again
        self._pathlist.observe(self._on_pathlist_select, names='value')
        self._dircontent.observe(self._on_dircontent_select, names='value')
        self._filename.observe(self._on_filename_change, names='value')

        # Set the state of the select Button
        if self._gb.layout.display is None:
            selected = os.path.join(self._selected_path,
                                    self._selected_filename)

            # filename value is empty or equals the selected value
            if ((filename == '') or
                (os.path.join(path, filename) == selected)) \
                    and self._include_files:
                self._select.disabled = True
            else:
                self._select.disabled = False

    def _on_pathlist_select(self, change):
        """Handler for when a new path is selected"""
        self._set_form_values(change['new'], self._filename.value)

    def _on_dircontent_select(self, change):
        """Handler for when a folder entry is selected"""
        new_path = update_path(self._pathlist.value, change['new'])

        # Check if folder or file
        if os.path.isdir(new_path):
            path = new_path
            filename = self._filename.value
        elif os.path.isfile(new_path):
            path = self._pathlist.value
            filename = change['new']

        self._set_form_values(path, filename)

    def _on_filename_change(self, change):
        """Handler for when the filename field changes"""
        self._set_form_values(self._pathlist.value, change['new'])

    def _on_select_click(self, b):
        """Handler for when the select button is clicked"""
        if self._gb.layout.display is 'none':
            self._gb.layout.display = None
            self._cancel.layout.display = None

            # Show the form with the correct path and filename
            if (self._selected_path and self._selected_filename) or \
                    (self._selected_path and not self._include_files):
                path = self._selected_path
                filename = self._selected_filename
            else:
                path = self._default_path
                filename = self._default_filename

            self._set_form_values(path, filename)

        else:
            self._gb.layout.display = 'none'
            self._cancel.layout.display = 'none'
            self._select.description = self._change_desc
            self._selected_path = self._pathlist.value
            self._selected_filename = self._filename.value
            # self._default_path = self._selected_path
            # self._default_filename = self._selected_filename

            selected = os.path.join(self._selected_path,
                                    self._selected_filename)

            if not self._include_files and os.path.isdir(selected):
                selected = selected.rstrip(os.path.sep)

            if os.path.isfile(selected):
                self._label.value = self._LBL_TEMPLATE.format(
                    selected, 'orange')
            else:
                self._label.value = self._LBL_TEMPLATE.format(
                    selected, 'green')

    def _on_cancel_click(self, b):
        """Handler for when the cancel button is clicked"""
        self._gb.layout.display = 'none'
        self._cancel.layout.display = 'none'
        self._select.disabled = False

    def reset(self, path=None, filename=None):
        """Reset the form to the default path and filename"""
        self._selected_path = ''
        self._selected_filename = ''

        self._label.value = self._LBL_TEMPLATE.format(
            self._LBL_NOFILE if self._include_files else
            self._LBL_NOFOLDER if self._include_folders else "", 'black')

        if path is not None:
            self._default_path = path.rstrip(os.path.sep)

        if filename is not None:
            self._default_filename = filename

        self._set_form_values(self._default_path, self._default_filename)

    def refresh(self):
        """Re-render the form"""
        self._set_form_values(self._pathlist.value, self._filename.value)

    @property
    def show_hidden(self):
        """Get current number of rows"""
        return self._show_hidden

    @show_hidden.setter
    def show_hidden(self, hidden):
        """Set number of rows"""
        self._show_hidden = hidden
        self.refresh()

    @property
    def rows(self):
        """Get current number of rows"""
        return self._dircontent.rows

    @rows.setter
    def rows(self, rows):
        """Set number of rows"""
        self._dircontent.rows = rows

    @property
    def title(self):
        """Get the title"""
        return self._title.value

    @title.setter
    def title(self, title):
        """Set the title"""
        self._title.value = title

        if title is '':
            self._title.layout.display = 'none'
        else:
            self._title.layout.display = None

    @property
    def default(self):
        """Get the default value"""
        return os.path.join(self._default_path, self._default_filename)

    @property
    def default_path(self):
        """Get the default_path value"""
        return self._default_path

    @default_path.setter
    def default_path(self, path):
        """Set the default_path"""
        self._default_path = path.rstrip(os.path.sep)
        self._default = os.path.join(self._default_path, self._filename.value)
        self._set_form_values(self._default_path, self._filename.value)

    @property
    def default_filename(self):
        """Get the default_filename value"""
        return self._default_filename

    @default_filename.setter
    def default_filename(self, filename):
        """Set the default_filename"""
        self._default_filename = filename
        self._default = os.path.join(self._pathlist.value,
                                     self._default_filename)
        self._set_form_values(self._pathlist.value, self._default_filename)

    @property
    def selected(self):
        """Get selected value"""
        return os.path.join(self._selected_path, self._selected_filename)

    @property
    def selected_path(self):
        """Get selected_path value"""
        return self._selected_path

    @property
    def selected_filename(self):
        """Get the selected_filename"""
        return self._selected_filename

    def __repr__(self):
        str_ = ("FileChooser("
                "path='{0}', "
                "filename='{1}', "
                "show_hidden='{2}')").format(self._default_path,
                                             self._default_filename,
                                             self._show_hidden)
        return str_
Example #34
0
 def get_button(**kwargs):
     """
         Get Button.
     """
     return Button(**kwargs)
Example #35
0
    def __init__(self, signal_components: dict):
        """
        Summary:
            Object constructor.
        
        Arguments:
            signal_components - dictionary with the signal components.
            
        Returns:
            Nothing.
        """
        # Tab count (to keep track of the tab)
        self.count = 0

        self.signal_components = signal_components

        # List of data displayers
        self.data_displayers = [base_data_displayer_widget(signal_components)]

        self.wt_data_displayers = Tab(self.data_displayers)
        self.wt_data_displayers.set_title(self.count, f"Figure {self.count+1}")
        self.count += 1
        # Add and remove buttons
        self.wb_add = Button(description='Add', disabled=False, icon='Add')

        self.wb_remove = Button(description='Remove',
                                disabled=False,
                                icon='Remove')

        @self.wb_add.on_click
        def wb_add_on_click(b):
            # Append a new data displayer
            self.data_displayers.append(
                base_data_displayer_widget(signal_components))

            self.wt_data_displayers.children = self.data_displayers
            self.wt_data_displayers.set_title(self.count,
                                              f"Figure {self.count+1}")
            self.count += 1

        @self.wb_remove.on_click
        def wd_remove_on_click(b):

            if len(self.data_displayers) > 1:
                self.data_displayers.pop()
                self.count -= 1
            else:
                # Empty tab
                self.data_displayers = [
                    base_data_displayer_widget(signal_components)
                ]

            self.wt_data_displayers.children = self.data_displayers

        self.wb_save = Button(description='Save', disabled=False, icon='save')

        @self.wb_save.on_click
        def wb_save_on_click(b):

            # Create the output element in the JSON file
            _dict = self.dump()

            key = list(_dict.keys())[0]
            value = _dict[key]

            config.set_value(key, value)

        self.wb_load = Button(description='Load', disabled=False, icon='load')

        wfc_options = FileChooser(placeholder='Option file',
                                  description='Option file:',
                                  disabled=False)

        self.whb_load = HBox([self.wb_load, wfc_options])

        @self.wb_load.on_click
        def wb_load_on_click(b):

            if wfc_options.selected is not None:
                optionFile = open(wfc_options.selected)
                options = json.load(optionFile)

                self.initialize(options)

        super().__init__([self.wt_data_displayers, HBox([self.wb_add, self.wb_remove]),\
                          self.wb_save, self.whb_load])
Example #36
0
class TrendsWithPickTokensGUI:
    def __init__(self,
                 token_selector: TokensSelector,
                 update_handler: Callable = None):
        self.token_selector: TokensSelector = token_selector
        self.update_handler: Callable = update_handler

        self._page_size = IntSlider(
            description="Count",
            min=0,
            max=100,
            step=1,
            value=3,
            continuous_update=False,
            layout=Layout(width="300px"),
        )
        self._forward = Button(
            description=">>",
            button_style="Success",
            layout=Layout(width="40px", color="green"),
        )
        self._back = Button(
            description="<<",
            button_style="Success",
            layout=Layout(width="40px", color="green"),
        )
        self._split = ToggleButton(description="Split",
                                   layout=Layout(width="80px", color="green"))
        self._output = Output(layout=Layout(width="80%"))

    def setup(self):

        self._page_size.observe(self._update, "value")
        self._split.observe(self.split_changed, "value")
        self._forward.on_click(self._stepper_clicked)
        self._back.on_click(self._stepper_clicked)
        self.token_selector.on_selection_change_handler(self._update)

    def _stepper_clicked(self, b):

        _selected_indices = self.token_selector.get_selected_indices()
        _current_index = min(
            _selected_indices) if len(_selected_indices) > 0 else 0

        if b.description == "<<":
            _current_index = max(_current_index - self.page_size, 0)

        if b.description == ">>":
            _current_index = min(_current_index + self.page_size,
                                 len(self.token_selector) - self.page_size)

        self.token_selector.set_selected_indices(
            list(range(_current_index, _current_index + self.page_size)))

    def _update(self):
        if self.update_handler is not None:
            with self._output:
                tokens = self.selected_tokens()
                self.update_handler(self, tokens)

    def split_changed(self, *_):
        self._update()

    def layout(self):
        return VBox([
            HBox([self._back, self._forward, self._page_size, self._split]),
            HBox([self.token_selector.widget, self._output],
                 layout=Layout(width="98%")),
        ])

    def display(self, trends_data: TrendsData):
        self.token_selector.display(
            trends_data.gof_data.most_deviating_overview)

    @property
    def page_size(self) -> int:
        return self._page_size.value

    @property
    def split(self) -> bool:
        return self._split.value

    @property
    def selected_tokens(self) -> Sequence[str]:
        tokens: Sequence[str] = self.token_selector.get_selected_tokens()
        if len(tokens) == 0:
            tokens = self.token_selector[:self.page_size]
        return tokens

    @staticmethod
    def create(
        corpus: VectorizedCorpus,
        tokens: pd.DataFrame,
        n_columns: int = 3,
        token_sector_cls: TokensSelector = SelectMultipleTokensSelector,
        tokens_selected=None,
    ) -> "TrendsWithPickTokensGUI":

        gui = TrendsWithPickTokensGUI(
            token_selector=token_sector_cls(tokens),
            update_handler=lambda tokens, split:
            (tokens_selected or TrendsWithPickTokensGUI.default_tokens_plotter)
            (tokens=tokens, corpus=corpus, n_columns=n_columns, split=split),
        )
        return gui

    @staticmethod
    def default_tokens_plotter(tokens: Sequence[str], corpus: VectorizedCorpus,
                               n_columns: int, split: bool):
        indices: List[int] = [corpus.token2id[token] for token in tokens]
        p = plotter.yearly_token_distribution_multiple_line_plot(
            corpus,
            indices,
            width=1000,
            height=600,
            n_columns=n_columns if split else None,
        )
        if p is None:
            return
        show(p)
Example #37
0
 def _on_button_click(self, instance: widgets.Button):
     self._state_index = (self._state_index + 1) % self._nStates
     instance.icon = self.icon
     instance.tooltip = self.tooltip
     for listener in self._listeners:
         listener(self.state)
Example #38
0
    def __init__(self,
                 path=os.getcwd(),
                 filename='',
                 title='',
                 select_desc='Select',
                 change_desc='Change',
                 show_hidden=False,
                 directory=False,
                 **kwargs):

        self._select_desc = select_desc
        self._default_path = path
        self._show_hidden = show_hidden
        self._select_desc = select_desc
        self._change_desc = change_desc
        self._path = path

        self._updir = Button(description='Up Directory')

        self._dircontent = Select(rows=8,
                                  layout=Layout(width='auto',
                                                grid_area='dircontent'))
        self._cancel = Button(description='Cancel',
                              layout=Layout(width='auto', display='none'))
        self._select = Button(description=self._select_desc,
                              layout=Layout(width='auto'))

        self._label = HTML(value=self._LBL_TEMPLATE.format(
            self._LBL_NOFILE, 'black'),
                           placeholder='',
                           description='')

        self._title = HTML(value=title)

        if title is '':
            self._title.layout.display = 'none'

        self._updir.on_click(self._on_updir_click)
        self._select.on_click(self._on_select_click)
        self._cancel.on_click(self._on_cancel_click)

        # Layout
        self._gb = GridBox(children=[self._updir, self._dircontent],
                           layout=Layout(display='none',
                                         width='500px',
                                         grid_gap='0px 0px',
                                         grid_template_rows='auto auto',
                                         grid_template_columns='60% 40%',
                                         grid_template_areas='''
					'pathlist filename'
					'dircontent dircontent'
					'''))

        self._dircontent.observe(self._on_dircontent_select, names='value')

        buttonbar = HBox(children=[
            self._select,
            self._cancel,
            self._label,
        ],
                         layout=Layout(width='auto'))

        # Call setter to set initial form values
        self._set_form_values(self._path)

        # Call VBox super class __init__
        super().__init__(children=[
            self._gb,
            buttonbar,
        ],
                         layout=Layout(width='auto'),
                         **kwargs)
Example #39
0
    def __init__(self):
        
        micron_units = Label('micron')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout={'width':'25%'}
        widget_layout = {'width': '15%'}
        units_button_layout ={'width':'15%'}
        desc_button_layout={'width':'45%'}

        param_name1 = Button(description='tumor_radius', disabled=True, layout=name_button_layout)
        param_name1.style.button_color = 'lightgreen'

        self.tumor_radius = FloatText(
          value=250.0,
          step=10,
          style=style, layout=widget_layout)

        param_name2 = Button(description='oncoprotein_mean', disabled=True, layout=name_button_layout)
        param_name2.style.button_color = 'tan'

        self.oncoprotein_mean = FloatText(
          value=1.0,
          step=0.1,
          style=style, layout=widget_layout)

        param_name3 = Button(description='oncoprotein_sd', disabled=True, layout=name_button_layout)
        param_name3.style.button_color = 'lightgreen'

        self.oncoprotein_sd = FloatText(
          value=0.25,
          step=0.01,
          style=style, layout=widget_layout)

        param_name4 = Button(description='oncoprotein_min', disabled=True, layout=name_button_layout)
        param_name4.style.button_color = 'tan'

        self.oncoprotein_min = FloatText(
          value=0.0,
          step=0.01,
          style=style, layout=widget_layout)

        param_name5 = Button(description='oncoprotein_max', disabled=True, layout=name_button_layout)
        param_name5.style.button_color = 'lightgreen'

        self.oncoprotein_max = FloatText(
          value=2,
          step=0.1,
          style=style, layout=widget_layout)

        units_button1 = Button(description='micron', disabled=True, layout=units_button_layout) 
        units_button1.style.button_color = 'lightgreen'
        units_button2 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button2.style.button_color = 'tan'
        units_button3 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button3.style.button_color = 'lightgreen'
        units_button4 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button4.style.button_color = 'tan'
        units_button5 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button5.style.button_color = 'lightgreen'

        desc_button1 = Button(description='initial tumor radius', disabled=True, layout=desc_button_layout) 
        desc_button1.style.button_color = 'lightgreen'
        desc_button2 = Button(description='mean oncoprotein value p at start', disabled=True, layout=desc_button_layout) 
        desc_button2.style.button_color = 'tan'
        desc_button3 = Button(description='standard deviation of oncoprotein p at start', disabled=True, layout=desc_button_layout) 
        desc_button3.style.button_color = 'lightgreen'
        desc_button4 = Button(description='p is not allowed to fall below this value', disabled=True, layout=desc_button_layout) 
        desc_button4.style.button_color = 'tan'
        desc_button5 = Button(description='p is not allowed to exceed this value', disabled=True, layout=desc_button_layout) 
        desc_button5.style.button_color = 'lightgreen'

        row1 = [param_name1, self.tumor_radius, units_button1, desc_button1] 
        row2 = [param_name2, self.oncoprotein_mean, units_button2, desc_button2] 
        row3 = [param_name3, self.oncoprotein_sd, units_button3, desc_button3] 
        row4 = [param_name4, self.oncoprotein_min, units_button4, desc_button4] 
        row5 = [param_name5, self.oncoprotein_max, units_button5, desc_button5] 

        box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%')
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)

        self.tab = VBox([
          box1,
          box2,
          box3,
          box4,
          box5,
        ])
class GUI(object):

    _BUTTONS = {
        "backstep": {
            "icon": "step-backward",
            "tooltip": "Step to the previous instruction",
        },
        "step": {
            "icon": "step-forward",
            "tooltip": "Step to the next instruction",
        },
        "previous": {
            "icon": "reply",
            "tooltip": "Go to th previous sourceline",
        },
        "next": {
            "icon": "share",
            "tooltip": "Go to the next sourceline",
        },
        "start": {
            "icon": "arrow-up",
            "tooltip": "Go to the start of the program",
        },
        "finish": {
            "icon": "arrow-down",
            "tooltip": "Go to the end of the program",
        },
        "reverse": {
            "icon": "fast-backward",
            "tooltip": "Continue execution backwards until breakpoint is hit",
        },
        "continue": {
            "icon": "fast-forward",
            "tooltip": "Continue execution until breakpoint is hit",
        },
    }

    def __init__(self):
        # Stores the respective line number and variable changes for each
        # exection step
        self._tracer = TimeTravelTracer()
        self._current_state = None
        self._debugger = None

        self._code_output = HTML()
        self._var_output = Output()
        self._watchpoint_output = Output()
        self._breakpoint_output = Output()

        self._diff_slider = IntSlider(
            min=1,
            readout=False,
            layout=Layout(width="99%"),
            tooltip="Execution timeline",
        )
        self._diff_slider.observe(self._handle_diff_slider, names="value")

        self._autoplay = Play(
            tooltip="Automatic playback of the execution",
            layout=Layout(height="30px"),
        )
        self._auto_link = jsdlink((self._autoplay, "value"),
                                  (self._diff_slider, "value"))

        self._speed_slider = IntSlider(description="Delay (ms)",
                                       min=100,
                                       max=1000,
                                       step=100,
                                       value=500)
        self._speed_link = jsdlink((self._speed_slider, "value"),
                                   (self._autoplay, "interval"))

        self._reverse_autoplay = ToggleButton(
            value=False,
            icon="history",
            tooltip="Reverse autoplay",
            layout=Layout(width="40px"),
        )
        self._reverse_autoplay.observe(self._handle_reverse_button)

        self._watchpoint_input = Text(
            layout=Layout(width="150px"),
            placeholder="Watch expression",
        )
        self._add_watchpoint = Button(
            icon="plus",
            tooltip="Add an expression or variable to watch",
            layout=Layout(width="50px"),
        )
        self._add_watchpoint.on_click(self.watch_command)

        self._watchpoint_dropdown = Dropdown(layout=Layout(width="150px"), )
        self._remove_watchpoint = Button(
            icon="trash",
            tooltip="Remove a watchpoint",
            layout=Layout(width="50px"),
        )
        self._remove_watchpoint.on_click(self.unwatch_command)

        self._breakpoint_layout = GridspecLayout(3, 1)

        self._add_breakpoint = Button(
            icon="plus",
            tooltip="Add a breakpoint",
            name="breakpoint_button",
            layout=Layout(width="40px"),
        )
        self._add_breakpoint.on_click(self._handle_breakpoint)

        self._disable_breakpoint_button = Button(
            icon="eye-slash",
            tooltip="Disable breakpoint",
            layout=Layout(width="50px"),
        )
        self._disable_breakpoint_button.on_click(self.disable_command)

        self._remove_breakpoint_button = Button(
            icon="trash",
            tooltip="Remove breakpoint",
            layout=Layout(width="50px"),
        )
        self._remove_breakpoint_button.on_click(self.delete_command)

        self._breakpoint_dropdown = Dropdown(layout=Layout(width="70px"))

        self._function_dropdown = Dropdown(layout=Layout(width="200px"))
        self._function_dropdown.disabled = True
        self._breakpoint_type = Dropdown(
            options=["Line", "Function", "Conditional"],
            value="Line",
            layout=Layout(width="100px"),
        )

        self._breakpoint_type.observe(self._handle_breakpoint_type,
                                      names="value")

        self._condition_input = Text(placeholder="Enter condition",
                                     layout=Layout(width="200px"))
        self._condition_input.disabled = True

        self._line_input = Text(
            placeholder="Line Number",
            name="line_input",
            layout=Layout(width="100px"),
        )

        self._breakpoint_layout = VBox([
            HBox([
                self._add_breakpoint,
                self._breakpoint_type,
                self._function_dropdown,
                self._line_input,
                self._condition_input,
                self._breakpoint_dropdown,
                self._remove_breakpoint_button,
                self._disable_breakpoint_button,
            ]),
            self._breakpoint_output,
        ])

        self._search_input = Text(placeholder="Search...")
        self._search_input.observe(self._handle_search_input, names="value")

        self._search_results = Output()
        self._search_layout = VBox([
            self._search_input,
            self._search_results,
        ])

        # Remove shadows from scrolling
        style = """
            <style>
               .jupyter-widgets-output-area .output_scroll {
                    border-radius: unset !important;
                    -webkit-box-shadow: unset !important;
                    box-shadow: unset !important;
                }
            </style>
            """
        display(HTML(style))

        for key, item in self._BUTTONS.items():
            self.register_button(key, **item)

        self._code_layout = GridspecLayout(4, 4, grid_gap="20px")

        self._code_layout[0:4, 0:3] = HBox(
            [self._code_output],
            layout=Layout(height="500px",
                          overflow_y="scroll",
                          border="2px solid black"),
        )
        self._code_layout[0:2, 3] = self._var_output
        self._code_layout[2:4, 3] = VBox([
            HBox([self._add_watchpoint, self._watchpoint_input]),
            HBox([self._remove_watchpoint, self._watchpoint_dropdown]),
            self._watchpoint_output,
        ])

        self._code_nav_layout = VBox([
            HBox([
                *self.get_buttons(),
                self._autoplay,
                self._reverse_autoplay,
                self._speed_slider,
            ]),
            self._diff_slider,
            self._code_layout,
        ])

        self._main_layout = Tab(
            [
                self._code_nav_layout,
                self._breakpoint_layout,
                self._search_layout,
            ],
            layout=Layout(height="650px"),
        )

        self._main_layout.set_title(0, "Code")
        self._main_layout.set_title(1, "Breakpoints")
        self._main_layout.set_title(2, "Search")

        display(self._main_layout)

    def __enter__(self, *args, **kwargs):
        self._tracer.set_trace()

    def __exit__(self, *args, **kwargs):
        diffs, source_map = self._tracer.get_trace()
        search_engine = SearchEngine()
        self._debugger = TimeTravelDebugger(diffs, source_map, self.update,
                                            search_engine)
        self._debugger.start_debugger()
        self._diff_slider.max = len(diffs) - 1
        self._function_dropdown.options = self._debugger.source_map.keys()

    def get_buttons(self, *keys):
        if not keys:
            return [
                self._BUTTONS[key]["button"] for key in self._BUTTONS.keys()
            ]
        return [self._BUTTONS[key]["button"] for key in keys]

    def register_button(self, key, **kwargs):
        button = Button(description="", layout=Layout(width="40px"), **kwargs)
        func = getattr(self, key + "_command")
        button.on_click(func)
        self._BUTTONS[key]["button"] = button

    def update(self, state=None):
        if state is not None:
            self._current_state = state

        self._diff_slider.value = self._debugger._state_machine._exec_point

        self._BUTTONS["previous"]["button"].disabled = self._debugger.at_start
        self._BUTTONS["start"]["button"].disabled = self._debugger.at_start
        self._BUTTONS["backstep"]["button"].disabled = self._debugger.at_start
        self._BUTTONS["next"]["button"].disabled = self._debugger.at_end
        self._BUTTONS["finish"]["button"].disabled = self._debugger.at_end
        self._BUTTONS["step"]["button"].disabled = self._debugger.at_end

        self._breakpoint_dropdown.options = [
            b.id for b in self._debugger.breakpoints
        ]
        self._watchpoint_dropdown.options = [
            b.id for b in self._debugger.watchpoints
        ]

        self.list_command()

        with self._var_output:
            clear_output(wait=True)
            self.print_command()

        with self._breakpoint_output:
            clear_output(wait=True)
            self.breakpoints_command()

        with self._watchpoint_output:
            clear_output(wait=True)
            self.list_watch_command()

    def log(self, *objects, sep=" ", end="\n", flush=False):
        """Like print(), but always sending to file given at initialization,
        and always flushing"""
        print(*objects, sep=sep, end=end, flush=True)

    # COMMANDS
    def print_command(self, arg=""):
        """Print all variables or pass an expression to evaluate in the
        current context"""
        # Shorthand such that the following code is not as lengthy
        curr_vars = self._current_state
        template = "|`{}`|{}|`{!r}`|"
        header = "| Variable | Type | Value |"
        split = "| --- | --- | --- |"

        variable_table = header + "\n" + split + "\n"
        variable_table += "\n".join(
            template.format(var, type(curr_vars[var]), curr_vars[var])
            for var in curr_vars if not var.startswith("__"))

        display(Markdown(variable_table))

    def step_command(self, arg=""):
        """ Step to the next instruction """
        self._debugger.step_forward()

    def backstep_command(self, arg=""):
        """ Step to the previous instruction """
        self._debugger.step_backward()

    def list_command(self, arg=""):
        """Show current function. If arg is given, show its source code."""
        display_current_line = self._debugger.curr_line

        code = self._debugger.get_source_for_func()

        source_lines = open(code["filename"]).read()

        css = f"""
        <style>
        {cssfile}
        </style>
        """

        lexer = lexers.get_lexer_by_name("python")
        formatter = formatters.HtmlFormatter(
            linenos=True,
            anchorlinenos=True,
            full=True,
            linespans=True,
            wrapcode=True,
        )
        coloured = highlight(source_lines, lexer=lexer, formatter=formatter)

        doc = html.fromstring(coloured)

        current_line_breakpoint = False

        # Highlight all breakpoints on the current file
        for bp in self._debugger.breakpoints:
            if self._debugger.curr_diff.file_name != bp.abs_filename:
                continue
            if bp.breakpoint_type != BPType.FUNC:
                elem = doc.get_element_by_id(f"True-{bp.lineno}", None)
                if bp.lineno == display_current_line:
                    current_line_breakpoint = True
                if elem is not None:
                    elem.set("class", "breakpoint")
                    if not bp.active:
                        elem.set("class", "inactive")

        elem = doc.get_element_by_id(f"True-{display_current_line}", None)
        if elem is not None:
            if not current_line_breakpoint and not self._autoplay._playing:
                elem.set("class", "currentline")
            elif self._autoplay._playing:
                elem.set("class", "currentline-running")
            else:
                elem.set("class", "hit")

        coloured = html.tostring(doc).decode("utf-8").strip()

        self._code_output.value = css + coloured

    def next_command(self, arg=""):
        """ Step to the next source line """
        self._debugger.next()

    def previous_command(self, arg=""):
        """ Step to the previous source line """
        self._debugger.previous()

    def finish_command(self, arg=""):
        """ Finish the current function execution """
        self._debugger.finish()

    def start_command(self, arg=""):
        """ Go to start of the current function call """
        self._debugger.start()

    def continue_command(self, arg=""):
        """ Continue execution forward until a breakpoint is hit """
        self._debugger.continue_()

    def reverse_command(self, arg=""):
        """ Continue execution backward until a breakpoint is hit """
        self._debugger.reverse()

    def watch_command(self, change):
        """ Insert a watchpoint """
        arg = self._watchpoint_input.value
        self._debugger.add_watchpoint(expression=arg)
        self._watchpoint_input.value = ""
        self.update()

    def list_watch_command(self):
        header = "| ID | Expression | Value |\n"
        split = "|---|---|---|\n"
        template = "|{}|`{}`|`{!r}`|\n"
        wpstr = header + split

        for wp in self._debugger.watchpoints:
            wpstr += template.format(*wp)

        display(Markdown(wpstr))

    def unwatch_command(self, change):
        """ Remove a watchpoint """
        arg = self._watchpoint_dropdown.value
        if not arg:
            return
        if not self._debugger.remove_watchpoint(int(arg)):
            print(f"Watchpoint with id {arg} does not exist.")
        else:
            print(f"Successfully removed watchpoint {arg}.")
            self.update()

    def break_command(self, arg=""):
        """ Insert a breakpoint at the given location """
        res = None
        # Find out which type of breakpoint we want to insert
        if arg.isnumeric():
            # Line breakpoint
            res = self._debugger.add_breakpoint(arg, "line")
        elif ":" not in arg:
            # Function breakpoint for different file
            res = self._debugger.add_breakpoint(arg, "func")
        else:
            filename, function_name = arg.split(":")
            res = self._debugger.add_breakpoint(function_name,
                                                "func",
                                                filename=filename)

        if res is not None:
            print(f"Breakpoint {res.id} added.")
        else:
            print("Could not add breakpoint.")

    def breakpoints_command(self, arg=""):
        """ List all breakpoints """
        header = "| ID | Type | Location | Status | Condition |\n"
        split = "|---|---|---|---|---|\n"

        bpstr = header + split

        for bp in self._debugger.breakpoints:
            bpstr += "|" + "|".join(bp) + "|\n"

        display(Markdown(bpstr))

    def delete_command(self, change):
        """ Remove the given breakpoint """
        arg = self._breakpoint_dropdown.value
        if not arg:
            return
        self._debugger.remove_breakpoint(int(arg))
        self.update()

    def disable_command(self, arg=""):
        """ Disable the given breakpoint """
        arg = self._breakpoint_dropdown.value
        if not arg:
            return
        self._debugger.disable_breakpoint(int(arg))
        self.update()

    def enable_command(self, arg=""):
        """ Enable the given breakpoint """
        self._debugger.enable_breakpoint(int(arg))

    def _handle_diff_slider(self, change):
        braked = self._debugger.step_to_index(
            change["new"], ignore_breakpoints=self._autoplay._playing)
        if braked:
            self._autoplay._playing = False

    def _handle_reverse_button(self, change):
        self._autoplay.step = -self._autoplay.step

    def _handle_breakpoint(self, change):
        type = self._breakpoint_type.value
        function = self._function_dropdown.value
        line = self._line_input.value
        condition = self._condition_input.value

        if type != "Function":
            if not line.isnumeric() or line is None:
                self._line_input.value = ""
                self._line_input.placeholder = "Please enter a valid number!"
                return

        if type == "Conditional":
            try:
                eval(condition)
            except SyntaxError:
                if self._condition_input.value:
                    self._condition_input.placeholder = "Invalid expression!"
                self._condition_input.value = ""
                return

            except NameError:
                pass

        if type == "Function":
            self._debugger.add_breakpoint(funcname=function)
        if type == "Line":
            self._debugger.add_breakpoint(lineno=line)
        if type == "Conditional":
            self._debugger.add_breakpoint(lineno=line, cond=condition)

        self.update()

    def _handle_breakpoint_type(self, change):
        self._function_dropdown.disabled = change["new"] != "Function"
        self._condition_input.disabled = change["new"] != "Conditional"
        self._line_input.disabled = change["new"] == "Function"

    def _handle_search_input(self, change):
        try:
            input = change["new"]
            event_type, query = input.split(" ", 1)
            events = self._debugger.search(event_type, query)
        except:
            return

        with self._search_results:
            clear_output()
            for event in events:
                goto = Button(
                    icon="angle-right",
                    layout=Layout(width="30px", height="30px"),
                )
                goto.on_click(lambda change: self._debugger.step_to_index(
                    event.exec_point, ignore_breakpoints=True))
                display(HBox([goto, Label(value=str(event))]))
Example #41
0
    def __init__(self):

        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout = {'width': '25%'}
        widget_layout = {'width': '15%'}
        units_button_layout = {'width': '15%'}
        desc_button_layout = {'width': '45%'}

        param_name1 = Button(description='persistence_time',
                             disabled=True,
                             layout=name_button_layout)
        param_name1.style.button_color = 'lightgreen'

        self.persistence_time = FloatText(value=10,
                                          step=1,
                                          style=style,
                                          layout=widget_layout)

        param_name2 = Button(description='migration_speed',
                             disabled=True,
                             layout=name_button_layout)
        param_name2.style.button_color = 'tan'

        self.migration_speed = FloatText(value=2,
                                         step=0.1,
                                         style=style,
                                         layout=widget_layout)

        param_name3 = Button(description='migration_bias',
                             disabled=True,
                             layout=name_button_layout)
        param_name3.style.button_color = 'lightgreen'

        self.migration_bias = FloatText(value=1.0,
                                        step=0.1,
                                        style=style,
                                        layout=widget_layout)

        param_name4 = Button(description='fixed_persistence',
                             disabled=True,
                             layout=name_button_layout)
        param_name4.style.button_color = 'tan'

        self.fixed_persistence = Checkbox(value=False,
                                          style=style,
                                          layout=widget_layout)

        param_name5 = Button(description='number_of_cells',
                             disabled=True,
                             layout=name_button_layout)
        param_name5.style.button_color = 'lightgreen'

        self.number_of_cells = IntText(value=3,
                                       step=0.1,
                                       style=style,
                                       layout=widget_layout)

        units_button1 = Button(description='min',
                               disabled=True,
                               layout=units_button_layout)
        units_button1.style.button_color = 'lightgreen'
        units_button2 = Button(description='micron/min',
                               disabled=True,
                               layout=units_button_layout)
        units_button2.style.button_color = 'tan'
        units_button3 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button3.style.button_color = 'lightgreen'
        units_button4 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button4.style.button_color = 'tan'
        units_button5 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button5.style.button_color = 'lightgreen'

        desc_button1 = Button(description='mean persistence time',
                              disabled=True,
                              layout=desc_button_layout)
        desc_button1.style.button_color = 'lightgreen'
        desc_button2 = Button(description='migration speed',
                              disabled=True,
                              layout=desc_button_layout)
        desc_button2.style.button_color = 'tan'
        desc_button3 = Button(description='migration bias parameter',
                              disabled=True,
                              layout=desc_button_layout)
        desc_button3.style.button_color = 'lightgreen'
        desc_button4 = Button(
            description=
            'true if each migration path has same duration (future PhysiCell versions)',
            disabled=True,
            layout=desc_button_layout)
        desc_button4.style.button_color = 'tan'
        desc_button5 = Button(description='number of cell tracks to simulate',
                              disabled=True,
                              layout=desc_button_layout)
        desc_button5.style.button_color = 'lightgreen'

        row1 = [
            param_name1, self.persistence_time, units_button1, desc_button1
        ]
        row2 = [param_name2, self.migration_speed, units_button2, desc_button2]
        row3 = [param_name3, self.migration_bias, units_button3, desc_button3]
        row4 = [
            param_name4, self.fixed_persistence, units_button4, desc_button4
        ]
        row5 = [param_name5, self.number_of_cells, units_button5, desc_button5]

        box_layout = Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            width='100%')
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)

        self.tab = VBox([
            box1,
            box2,
            box3,
            box4,
            box5,
        ])
Example #42
0
    def _widget(self):
        """ Create IPython widget for display within a notebook """
        try:
            return self._cached_widget
        except AttributeError:
            pass

        try:
            from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML, Accordion
        except ImportError:
            self._cached_widget = None
            return None

        layout = Layout(width="150px")

        if self.dashboard_link:
            dashboard_link = (
                '<p><b>Dashboard: </b><a href="%s" target="_blank">%s</a></p>\n'
                % (self.dashboard_link, self.dashboard_link))
        else:
            dashboard_link = ""

        if self.jupyter_link:
            jupyter_link = (
                '<p><b>Jupyter: </b><a href="%s" target="_blank">%s</a></p>\n'
                % (self.jupyter_link, self.jupyter_link))
        else:
            jupyter_link = ""

        title = "<h2>%s</h2>" % self._cluster_class_name
        title = HTML(title)
        dashboard = HTML(dashboard_link)
        jupyter = HTML(jupyter_link)

        status = HTML(self._widget_status(), layout=Layout(min_width="150px"))

        if self._supports_scaling:
            request = IntText(self.initial_node_count,
                              description="Nodes",
                              layout=layout)
            scale = Button(description="Scale", layout=layout)

            minimum = IntText(0, description="Minimum", layout=layout)
            maximum = IntText(0, description="Maximum", layout=layout)
            adapt = Button(description="Adapt", layout=layout)

            accordion = Accordion(
                [HBox([request, scale]),
                 HBox([minimum, maximum, adapt])],
                layout=Layout(min_width="500px"),
            )
            accordion.selected_index = None
            accordion.set_title(0, "Manual Scaling")
            accordion.set_title(1, "Adaptive Scaling")

            def adapt_cb(b):
                self.adapt(minimum=minimum.value, maximum=maximum.value)
                update()

            adapt.on_click(adapt_cb)

            def scale_cb(b):
                with log_errors():
                    n = request.value
                    with suppress(AttributeError):
                        self._adaptive.stop()
                    self.scale(n)
                    update()

            scale.on_click(scale_cb)
        else:
            accordion = HTML("")

        box = VBox([title, HBox([status, accordion]), jupyter, dashboard])

        self._cached_widget = box

        def update():
            self.close_when_disconnect()
            status.value = self._widget_status()

        pc = PeriodicCallback(update, 500)  # , io_loop=self.loop)
        self.periodic_callbacks["cluster-repr"] = pc
        pc.start()

        return box
class NewSageExplorer(VBox):
    """Sage Explorer in Jupyter Notebook"""

    value = Any()

    def __init__(self, obj=None):
        """
        TESTS::

            sage: from new_sage_explorer.new_sage_explorer import NewSageExplorer
            sage: t = StandardTableaux(15).random_element()
            sage: widget = NewSageExplorer(t)
        """
        super(NewSageExplorer, self).__init__()
        self.history = []
        self.set_value(obj)

    def compute(self):
        obj = self.value
        self.titlebox = ExplorerTitle(obj)
        self.description = ExplorerDescription(obj)
        self.props = ExplorerProperties(obj)
        def handle_click(e):
            self.set_value(e.source.value)
        for v in self.props.children:
            if type(v) == ExplorableValue:
                v.clc.on_dom_event(handle_click)
        self.propsbox = VBox([self.description, self.props])
        self.titlebox.add_class('titlebox')
        self.titlebox.add_class('lightborder')
        self.visualbox = ExplorerVisual(obj)
        self.visualbox.add_class('visualbox')

        self.top = VBox(
            [self.titlebox,
             HBox(
                 [self.propsbox, Separator(' '), self.visualbox],
                         layout=Layout(margin='10px 0')
             )
            ],
            layout=Layout(border='1px solid yellow')
        )

        self.menusbox = ExplorerMenus(obj)
        self.namingbox = ExplorerNaming(obj)
        self.searchbox = ExplorerMethodSearch(obj)
        self.inputbox = Text()
        self.inputbutton = Button(description='-', layout=Layout(width='30px'))
        self.gobutton = Button(description='Run!', tooltip='Run the method with specified arguments')
        def compute_selected_method(button):
            args = []
            if self.inputbox.value:
                args = self.inputbox.value.split(',')
            try:
            #    if AlarmInterrupt:
            #        alarm(TIMEOUT)
                out = self.searchbox.get_member()(obj, *args)
            #        if AlarmInterrupt:
            #            cancel_alarm()
            #except AlarmInterrupt:
            #    self.output.value = to_html("Timeout!")
            except Exception as e:
                self.outputbox.output.value = 'Error: %s; input=%s' % (e, str(args))
                return
            self.outputbox.output.value = '$%s$' % out
        self.gobutton.on_click(compute_selected_method)
        self.actionbox = HBox([
            self.namingbox,
            Separator('.'),
            self.searchbox,
            Separator('('),
            self.inputbox,
            self.inputbutton,
            Separator(')'),
            self.gobutton
        ])
        self.outputbox = ExplorerOutput(obj)
        self.helpbox = ExplorerHelp(obj)
        self.helpbox.update_title(self.description.content + " ..")

        self.bottom = VBox([self.actionbox, self.outputbox, self.helpbox])

        self.children = (self.top, self.bottom)

    def set_value(self, obj):
        r"""
        Set new math object `obj` to the explorer.

        TESTS::
            sage: from new_sage_explorer.new_sage_explorer import NewSageExplorer
            sage: from sage.combinat.partition import Partition
            sage: p = Partition([3,3,2,1])
            sage: e = NewSageExplorer(p)
            sage: e.get_value()
            [3, 3, 2, 1]
            sage: from sage.combinat.tableau import Tableau
            sage: t = Tableau([[1,2,3,4], [5,6]])
            sage: e.set_value(t)
            sage: e.get_value()
            [[1, 2, 3, 4], [5, 6]]
        """
        self.history.append(obj)
        self.value = obj
        self.compute()

    def get_value(self):
        r"""
        Return math object currently explored.

        TESTS::
            sage: from new_sage_explorer.new_sage_explorer import NewSageExplorer
            sage: from sage.combinat.partition import Partition
            sage: p = Partition([3,3,2,1])
            sage: e = NewSageExplorer(p)
            sage: e.get_value()
            [3, 3, 2, 1]
        """
        return self.value

    def pop_value(self):
        r"""
        Set again previous math object to the explorer.

        TESTS::
            sage: from new_sage_explorer.new_sage_explorer import NewSageExplorer
            sage: from sage.combinat.partition import Partition
            sage: p = Partition([3,3,2,1])
            sage: e = NewSageExplorer(p)
            sage: from sage.combinat.tableau import Tableau
            sage: t = Tableau([[1,2,3,4], [5,6]])
            sage: e.set_value(t)
            sage: e.get_value()
            [[1, 2, 3, 4], [5, 6]]
            sage: e.pop_value()
            sage: e.get_value()
            [3, 3, 2, 1]
        """
        if self.history:
            self.history.pop()
        if self.history:
            self.value = self.history[-1]
        else:
            self.value = None
Example #44
0
    def __init__(self):

        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout = {'width': '25%'}
        widget_layout = {'width': '15%'}
        units_button_layout = {'width': '15%'}
        desc_button_layout = {'width': '45%'}

        param_name1 = Button(description='random_seed',
                             disabled=True,
                             layout=name_button_layout)
        param_name1.style.button_color = 'lightgreen'

        self.random_seed = IntText(value=0,
                                   step=1,
                                   style=style,
                                   layout=widget_layout)

        param_name2 = Button(description='virion_uncoating_rate',
                             disabled=True,
                             layout=name_button_layout)
        param_name2.style.button_color = 'tan'

        self.virion_uncoating_rate = FloatText(value=0.05,
                                               step=0.01,
                                               style=style,
                                               layout=widget_layout)

        param_name3 = Button(description='uncoated_to_RNA_rate',
                             disabled=True,
                             layout=name_button_layout)
        param_name3.style.button_color = 'lightgreen'

        self.uncoated_to_RNA_rate = FloatText(value=0.05,
                                              step=0.01,
                                              style=style,
                                              layout=widget_layout)

        param_name4 = Button(description='protein_synthesis_rate',
                             disabled=True,
                             layout=name_button_layout)
        param_name4.style.button_color = 'tan'

        self.protein_synthesis_rate = FloatText(value=0.05,
                                                step=0.01,
                                                style=style,
                                                layout=widget_layout)

        param_name5 = Button(description='virion_assembly_rate',
                             disabled=True,
                             layout=name_button_layout)
        param_name5.style.button_color = 'lightgreen'

        self.virion_assembly_rate = FloatText(value=0.05,
                                              step=0.01,
                                              style=style,
                                              layout=widget_layout)

        param_name6 = Button(description='virion_export_rate',
                             disabled=True,
                             layout=name_button_layout)
        param_name6.style.button_color = 'tan'

        self.virion_export_rate = FloatText(value=0.005,
                                            step=0.001,
                                            style=style,
                                            layout=widget_layout)

        param_name7 = Button(description='max_infected_apoptosis_rate',
                             disabled=True,
                             layout=name_button_layout)
        param_name7.style.button_color = 'lightgreen'

        self.max_infected_apoptosis_rate = FloatText(value=0.001,
                                                     step=0.0001,
                                                     style=style,
                                                     layout=widget_layout)

        param_name8 = Button(description='max_apoptosis_half_max',
                             disabled=True,
                             layout=name_button_layout)
        param_name8.style.button_color = 'tan'

        self.max_apoptosis_half_max = FloatText(value=500,
                                                step=10,
                                                style=style,
                                                layout=widget_layout)

        param_name9 = Button(description='apoptosis_hill_power',
                             disabled=True,
                             layout=name_button_layout)
        param_name9.style.button_color = 'lightgreen'

        self.apoptosis_hill_power = FloatText(value=1,
                                              step=0.1,
                                              style=style,
                                              layout=widget_layout)

        param_name10 = Button(description='virion_uptake_rate',
                              disabled=True,
                              layout=name_button_layout)
        param_name10.style.button_color = 'tan'

        self.virion_uptake_rate = FloatText(value=1,
                                            step=0.1,
                                            style=style,
                                            layout=widget_layout)

        param_name11 = Button(description='virus_fraction_released_at_death',
                              disabled=True,
                              layout=name_button_layout)
        param_name11.style.button_color = 'lightgreen'

        self.virus_fraction_released_at_death = FloatText(value=0,
                                                          step=0.01,
                                                          style=style,
                                                          layout=widget_layout)

        param_name12 = Button(description='plot_scale',
                              disabled=True,
                              layout=name_button_layout)
        param_name12.style.button_color = 'tan'

        self.plot_scale = FloatText(value=100,
                                    step=10,
                                    style=style,
                                    layout=widget_layout)

        units_button1 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button1.style.button_color = 'lightgreen'
        units_button2 = Button(description='1/min',
                               disabled=True,
                               layout=units_button_layout)
        units_button2.style.button_color = 'tan'
        units_button3 = Button(description='1/min',
                               disabled=True,
                               layout=units_button_layout)
        units_button3.style.button_color = 'lightgreen'
        units_button4 = Button(description='1/min',
                               disabled=True,
                               layout=units_button_layout)
        units_button4.style.button_color = 'tan'
        units_button5 = Button(description='1/min',
                               disabled=True,
                               layout=units_button_layout)
        units_button5.style.button_color = 'lightgreen'
        units_button6 = Button(description='1/min',
                               disabled=True,
                               layout=units_button_layout)
        units_button6.style.button_color = 'tan'
        units_button7 = Button(description='1/min',
                               disabled=True,
                               layout=units_button_layout)
        units_button7.style.button_color = 'lightgreen'
        units_button8 = Button(description='virion',
                               disabled=True,
                               layout=units_button_layout)
        units_button8.style.button_color = 'tan'
        units_button9 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button9.style.button_color = 'lightgreen'
        units_button10 = Button(description='1/min',
                                disabled=True,
                                layout=units_button_layout)
        units_button10.style.button_color = 'tan'
        units_button11 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button11.style.button_color = 'lightgreen'
        units_button12 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button12.style.button_color = 'tan'

        desc_button1 = Button(description='',
                              tooltip='',
                              disabled=True,
                              layout=desc_button_layout)
        desc_button1.style.button_color = 'lightgreen'
        desc_button2 = Button(
            description='rate at which an internalized virion is uncoated',
            tooltip='rate at which an internalized virion is uncoated',
            disabled=True,
            layout=desc_button_layout)
        desc_button2.style.button_color = 'tan'
        desc_button3 = Button(
            description=
            'rate at which uncoated virion makes its mRNA available',
            tooltip='rate at which uncoated virion makes its mRNA available',
            disabled=True,
            layout=desc_button_layout)
        desc_button3.style.button_color = 'lightgreen'
        desc_button4 = Button(
            description='rate at mRNA creates complete set of proteins',
            tooltip='rate at mRNA creates complete set of proteins',
            disabled=True,
            layout=desc_button_layout)
        desc_button4.style.button_color = 'tan'
        desc_button5 = Button(
            description=
            'rate at which viral proteins are assembled into complete virion',
            tooltip=
            'rate at which viral proteins are assembled into complete virion',
            disabled=True,
            layout=desc_button_layout)
        desc_button5.style.button_color = 'lightgreen'
        desc_button6 = Button(
            description='rate at which a virion is exported from a live cell',
            tooltip='rate at which a virion is exported from a live cell',
            disabled=True,
            layout=desc_button_layout)
        desc_button6.style.button_color = 'tan'
        desc_button7 = Button(
            description='maximum rate of cell apoptosis due to viral infection',
            tooltip='maximum rate of cell apoptosis due to viral infection',
            disabled=True,
            layout=desc_button_layout)
        desc_button7.style.button_color = 'lightgreen'
        desc_button8 = Button(
            description=
            'viral load at which cells reach half max apoptosis rate',
            tooltip='viral load at which cells reach half max apoptosis rate',
            disabled=True,
            layout=desc_button_layout)
        desc_button8.style.button_color = 'tan'
        desc_button9 = Button(
            description='Hill power for viral load apoptosis response',
            tooltip='Hill power for viral load apoptosis response',
            disabled=True,
            layout=desc_button_layout)
        desc_button9.style.button_color = 'lightgreen'
        desc_button10 = Button(
            description='rate coefficient for virion endocytosis',
            tooltip='rate coefficient for virion endocytosis',
            disabled=True,
            layout=desc_button_layout)
        desc_button10.style.button_color = 'tan'
        desc_button11 = Button(
            description='fraction of internal virus released at cell death',
            tooltip='fraction of internal virus released at cell death',
            disabled=True,
            layout=desc_button_layout)
        desc_button11.style.button_color = 'lightgreen'
        desc_button12 = Button(description='scale for viral load coloring',
                               tooltip='scale for viral load coloring',
                               disabled=True,
                               layout=desc_button_layout)
        desc_button12.style.button_color = 'tan'

        row1 = [param_name1, self.random_seed, units_button1, desc_button1]
        row2 = [
            param_name2, self.virion_uncoating_rate, units_button2,
            desc_button2
        ]
        row3 = [
            param_name3, self.uncoated_to_RNA_rate, units_button3, desc_button3
        ]
        row4 = [
            param_name4, self.protein_synthesis_rate, units_button4,
            desc_button4
        ]
        row5 = [
            param_name5, self.virion_assembly_rate, units_button5, desc_button5
        ]
        row6 = [
            param_name6, self.virion_export_rate, units_button6, desc_button6
        ]
        row7 = [
            param_name7, self.max_infected_apoptosis_rate, units_button7,
            desc_button7
        ]
        row8 = [
            param_name8, self.max_apoptosis_half_max, units_button8,
            desc_button8
        ]
        row9 = [
            param_name9, self.apoptosis_hill_power, units_button9, desc_button9
        ]
        row10 = [
            param_name10, self.virion_uptake_rate, units_button10,
            desc_button10
        ]
        row11 = [
            param_name11, self.virus_fraction_released_at_death,
            units_button11, desc_button11
        ]
        row12 = [param_name12, self.plot_scale, units_button12, desc_button12]

        box_layout = Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            width='100%')
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)
        box6 = Box(children=row6, layout=box_layout)
        box7 = Box(children=row7, layout=box_layout)
        box8 = Box(children=row8, layout=box_layout)
        box9 = Box(children=row9, layout=box_layout)
        box10 = Box(children=row10, layout=box_layout)
        box11 = Box(children=row11, layout=box_layout)
        box12 = Box(children=row12, layout=box_layout)

        self.tab = VBox([
            box1,
            box2,
            box3,
            box4,
            box5,
            box6,
            box7,
            box8,
            box9,
            box10,
            box11,
            box12,
        ])
Example #45
0
    def make_controls(self):
        layout = Layout(width='100%', height="100%")
        button_begin = Button(icon="fast-backward", layout=layout)
        button_prev = Button(icon="backward", layout=layout)
        button_next = Button(icon="forward", layout=layout)
        button_end = Button(icon="fast-forward", layout=layout)
        #button_prop = Button(description="Propagate", layout=Layout(width='100%'))
        #button_train = Button(description="Train", layout=Layout(width='100%'))
        self.button_play = Button(icon="play", description="Play", layout=layout)
        step_down = Button(icon="sort-down", layout=Layout(width="95%", height="100%"))
        step_up = Button(icon="sort-up", layout=Layout(width="95%", height="100%"))
        up_down = HBox([step_down, step_up], layout=Layout(width="100%", height="100%"))
        refresh_button = Button(icon="refresh", layout=Layout(width="25%", height="100%"))

        self.position_text = IntText(value=0, layout=layout)

        self.control_buttons = HBox([
            button_begin,
            button_prev,
            #button_train,
            self.position_text,
            button_next,
            button_end,
            self.button_play,
            up_down,
            refresh_button
        ], layout=Layout(width='100%', height="100%"))
        length = (len(self.net.dataset.train_inputs) - 1) if len(self.net.dataset.train_inputs) > 0 else 0
        self.control_slider = IntSlider(description="Dataset index",
                                   continuous_update=False,
                                   min=0,
                                   max=max(length, 0),
                                   value=0,
                                   layout=Layout(width='100%'))
        if self.net.config["dashboard.dataset"] == "Train":
            length = len(self.net.dataset.train_inputs)
        else:
            length = len(self.net.dataset.test_inputs)
        self.total_text = Label(value="of %s" % length, layout=Layout(width="100px"))
        self.zoom_slider = FloatSlider(description="Zoom",
                                       continuous_update=False,
                                       min=0, max=1.0,
                                       style={"description_width": 'initial'},
                                       layout=Layout(width="65%"),
                                       value=self.net.config["svg_scale"] if self.net.config["svg_scale"] is not None else 0.5)

        ## Hook them up:
        button_begin.on_click(lambda button: self.goto("begin"))
        button_end.on_click(lambda button: self.goto("end"))
        button_next.on_click(lambda button: self.goto("next"))
        button_prev.on_click(lambda button: self.goto("prev"))
        self.button_play.on_click(self.toggle_play)
        self.control_slider.observe(self.update_slider_control, names='value')
        refresh_button.on_click(lambda widget: (self.update_control_slider(),
                                                self.output.clear_output(),
                                                self.regenerate()))
        step_down.on_click(lambda widget: self.move_step("down"))
        step_up.on_click(lambda widget: self.move_step("up"))
        self.zoom_slider.observe(self.update_zoom_slider, names='value')
        self.position_text.observe(self.update_position_text, names='value')
        # Put them together:
        controls = VBox([HBox([self.control_slider, self.total_text], layout=Layout(height="40px")),
                         self.control_buttons], layout=Layout(width='100%'))

        #net_page = VBox([control, self.net_svg], layout=Layout(width='95%'))
        controls.on_displayed(lambda widget: self.regenerate())
        return controls
Example #46
0
    def _display(self):
        step_slide = IntSlider(value=self.step,
                               min=-100,
                               max=100,
                               description='step')
        delay_text = IntSlider(value=self.delay,
                               min=10,
                               max=1000,
                               description='delay')
        checkbox_interpolate = Checkbox(self.interpolate,
                                        description='interpolate')
        checkbox_spin = Checkbox(self.spin, description='spin')
        spin_x_slide = IntSlider(self._spin_x,
                                 min=-1,
                                 max=1,
                                 description='spin_x')
        spin_y_slide = IntSlider(self._spin_y,
                                 min=-1,
                                 max=1,
                                 description='spin_y')
        spin_z_slide = IntSlider(self._spin_z,
                                 min=-1,
                                 max=1,
                                 description='spin_z')
        spin_speed_slide = FloatSlider(self._spin_speed,
                                       min=0,
                                       max=0.2,
                                       step=0.001,
                                       description='spin speed')
        bg_color = ColorPicker(value='white', description='background')
        bg_color.width = 100.
        # t_interpolation = FloatSlider(value=0.5, min=0, max=1.0, step=0.1)
        interpolation_type = Dropdown(value=self._iterpolation_type,
                                      options=['linear', 'spline'])

        camera_type = Dropdown(value=self.camera,
                               options=['perspective', 'orthographic'],
                               description='camera')

        link((step_slide, 'value'), (self, 'step'))
        link((delay_text, 'value'), (self, 'delay'))
        link((checkbox_interpolate, 'value'), (self, 'interpolate'))
        # link((t_interpolation, 'value'), (self, '_interpolation_t'))
        link((interpolation_type, 'value'), (self, '_iterpolation_type'))
        link((camera_type, 'value'), (self, 'camera'))
        link((bg_color, 'value'), (self._view, 'background'))

        # spin
        link((checkbox_spin, 'value'), (self, 'spin'))
        link((spin_x_slide, 'value'), (self, '_spin_x'))
        link((spin_y_slide, 'value'), (self, '_spin_y'))
        link((spin_z_slide, 'value'), (self, '_spin_z'))
        link((spin_speed_slide, 'value'), (self, '_spin_speed'))

        qtconsole_button = self._make_button_qtconsole()

        ibox = HBox([checkbox_interpolate, interpolation_type])
        center_button = self._make_button_center()
        render_button = self._show_download_image()
        center_render_hbox = HBox([center_button, render_button])

        v0_left = VBox([
            step_slide,
            delay_text,
            bg_color,
            ibox,
            camera_type,
            center_render_hbox,
            qtconsole_button,
        ])

        spin_box = VBox([
            checkbox_spin, spin_x_slide, spin_y_slide, spin_z_slide,
            spin_speed_slide
        ])

        drag_button = Button(description='widget drag: off',
                             tooltip='dangerous')

        def on_drag(drag_button):
            if drag_button.description == 'widget drag: off':
                self._view._set_draggable(True)
                drag_button.description = 'widget drag: on'
            else:
                self._view._set_draggable(False)
                drag_button.description = 'widget drag: off'

        drag_nb = Button(description='notebook drag: off', tooltip='dangerous')

        def on_drag_nb(drag_button):
            if drag_nb.description == 'notebook drag: off':
                self._view._set_notebook_draggable(True)
                drag_nb.description = 'notebook drag: on'
            else:
                self._view._set_notebook_draggable(False)
                drag_nb.description = 'notebook drag: off'

        reset_nb = Button(description='notebook: reset', tooltip='reset?')

        def on_reset(reset_nb):
            self._view._reset_notebook()

        dialog_button = Button(description='dialog', tooltip='make a dialog')

        def on_dialog(dialog_button):
            self._view._remote_call('setDialog', target='Widget')

        lucky_button = Button(description='lucky',
                              tooltip='try best to make a good layout')

        def on_being_lucky(dialog_button):
            self._view._move_notebook_to_the_right()
            self._view._remote_call('setDialog', target='Widget')

        drag_button.on_click(on_drag)
        drag_nb.on_click(on_drag_nb)
        reset_nb.on_click(on_reset)
        dialog_button.on_click(on_dialog)
        lucky_button.on_click(on_being_lucky)
        drag_box = HBox(
            [drag_button, drag_nb, reset_nb, dialog_button, lucky_button])

        gen_box = HBox([
            v0_left,
        ])
        theme_box = Box(
            [self._make_button_theme(),
             self._make_button_reset_theme()])
        hide_box = Box([])
        help_url_box = self._show_website()

        picked_box = HBox([
            self.picked_widget,
        ])
        component_slider = get_widget_by_name(self.repr_widget,
                                              'component_slider')
        repr_add_widget = self._make_add_repr_widget(component_slider)
        repr_box = HBox([self.repr_widget, repr_add_widget])
        repr_playground = self._make_selection_repr_buttons()
        export_image_box = HBox([self._make_button_export_image()])

        extra_list = [(drag_box, 'Drag'), (spin_box, 'spin_box'),
                      (picked_box, 'picked atom'),
                      (repr_playground, 'quick repr'),
                      (export_image_box, 'Image')]

        extra_box = Tab([w for w, _ in extra_list])
        [
            extra_box.set_title(i, title)
            for i, (_, title) in enumerate(extra_list)
        ]

        box_couple = [(gen_box, 'General'), (repr_box, 'Representation'),
                      (self._preference_widget, 'Preference'),
                      (theme_box, 'Theme'), (extra_box, 'Extra'),
                      (hide_box, 'Hide'), (help_url_box, 'Help')]

        for box in gen_box.children:
            make_default_slider_width(box)
        make_default_slider_width(self._preference_widget)

        tab = Tab([box for box, _ in box_couple])
        [tab.set_title(i, title) for i, (_, title) in enumerate(box_couple)]

        return tab
Example #47
0
class Core:
    # All constants that will be injected into global scope in the user"s cell
    global_constants = {
        "pi": pi
    }

    # All methods/fields from this class that will be exposed as global in user"s scope
    global_fields = {
        "canvas", "size", "width", "height",
        "mouse_x", "mouse_y", "mouse_is_pressed",
        "fill_style", "stroke_style",
        "clear", "background",
        "rect", "square", "fill_rect", "stroke_rect", "clear_rect",
        "fill_text", "stroke_text", "text_align",
        "draw_line",
        "circle", "fill_circle", "stroke_circle", "fill_arc", "stroke_arc",
        "print"
    }

    # All methods that user will be able to define and override
    global_methods = {
        "draw", "setup",
        "mouse_down", "mouse_up", "mouse_moved"
    }

    def __init__(self, globals_dict):
        self.status_text = display(Code(""), display_id=True)
        self._globals_dict = globals_dict
        self._methods = {}

        self.stop_button = Button(description="Stop")
        self.stop_button.on_click(self.on_stop_button_clicked)

        self.canvas = Canvas()
        self.output_text = ""
        self.width, self.height = DEFAULT_CANVAS_SIZE
        self.mouse_x = 0
        self.mouse_y = 0
        self.mouse_is_pressed = False

    ### Properties ###

    @property
    def mouse_x(self):
        return self._globals_dict["mouse_x"]

    @mouse_x.setter
    def mouse_x(self, val):
        self._globals_dict["mouse_x"] = val

    @property
    def mouse_y(self):
        return self._globals_dict["mouse_y"]

    @mouse_y.setter
    def mouse_y(self, val):
        self._globals_dict["mouse_y"] = val

    @property
    def mouse_is_pressed(self):
        return self._globals_dict["mouse_is_pressed"]

    @mouse_is_pressed.setter
    def mouse_is_pressed(self, val):
        self._globals_dict["mouse_is_pressed"] = val

    @property
    def width(self):
        return self._globals_dict["width"]

    @width.setter
    def width(self, val):
        self._globals_dict["width"] = val
        self.canvas.width = val

    @property
    def height(self):
        return self._globals_dict["height"]

    @height.setter
    def height(self, val):
        self._globals_dict["height"] = val
        self.canvas.height = val

    ### Library init ###

    # Updates last activity time
    @staticmethod
    def refresh_last_activity():
        global _sparkplug_last_activity
        _sparkplug_last_activity = time.time()

    # Creates canvas and starts thread
    def start(self, methods):
        self._methods = methods
        draw = self._methods.get("draw", None)
        
        if draw:
            self.print_status("Running...")
            display(self.stop_button)
        else:
            self.print_status("Done drawing")

        display(self.canvas)
        
        self.output_text_code = display(Code(self.output_text), display_id=True)

        self.canvas.on_mouse_down(self.on_mouse_down)
        self.canvas.on_mouse_up(self.on_mouse_up)
        self.canvas.on_mouse_move(self.on_mouse_move)

        thread = threading.Thread(target=self.loop)
        thread.start()

    def stop(self, message="Stopped"):
        global _sparkplug_running

        if not _sparkplug_running:
            return

        _sparkplug_running = False
        self.print_status(message)
        # Assuming we're using IPython to draw the canvas through the display() function.
        # Commenting this out for now, it throws exception since it does not derive BaseException
        # raise IpyExit

    # Loop method that handles drawing and setup
    def loop(self):
        global _sparkplug_active_thread_id, _sparkplug_running

        # Set active thread to this thread. This will stop any other active thread.
        current_thread_id = threading.current_thread().native_id
        _sparkplug_active_thread_id = current_thread_id
        _sparkplug_running = True
        self.refresh_last_activity()

        draw = self._methods.get("draw", None)
        setup = self._methods.get("setup", None)

        if setup:
            try:
                setup()
            except Exception as e:
                self.print_status("Error in setup() function: " + str(e))
                return

        while _sparkplug_running:
            if _sparkplug_active_thread_id != current_thread_id or time.time() - _sparkplug_last_activity > NO_ACTIVITY_THRESHOLD:
                self.stop("Stopped due to inactivity")
                return

            if not draw:
                return

            with hold_canvas(self.canvas):
                try:
                    draw()
                except Exception as e:
                    self.print_status("Error in draw() function: " + str(e))
                    return

            time.sleep(1 / FRAME_RATE)

    # Prints status to embedded error box
    def print_status(self, msg):
        self.status_text.update(Code(msg))
    
    # Prints output to embedded output box
    def print(self, msg):
        global _sparkplug_running
        self.output_text += str(msg) + "\n"

        if _sparkplug_running:
            self.output_text_code.update(Code(self.output_text))

    # Update mouse_x, mouse_y, and call mouse_down handler
    def on_mouse_down(self, x, y):
        self.refresh_last_activity()
        self.mouse_x, self.mouse_y = int(x), int(y)
        self.mouse_is_pressed = True

        mouse_down = self._methods.get("mouse_down", None)
        if mouse_down:
            mouse_down()

    # Update mouse_x, mouse_y, and call mouse_up handler
    def on_mouse_up(self, x, y):
        self.refresh_last_activity()
        self.mouse_x, self.mouse_y = int(x), int(y)
        self.mouse_is_pressed = False

        mouse_up = self._methods.get("mouse_up", None)
        if mouse_up:
            mouse_up()

    # Update mouse_x, mouse_y, and call mouse_moved handler
    def on_mouse_move(self, x, y):
        self.refresh_last_activity()
        self.mouse_x, self.mouse_y = int(x), int(y)

        mouse_moved = self._methods.get("mouse_moved", None)
        if mouse_moved:
            mouse_moved()
    
    def on_stop_button_clicked(self, button):
        self.stop()

    ### Global functions ###

    # Sets canvas size
    def size(self, *args):
        if len(args) == 2:
            self.width = args[0]
            self.height = args[1]

    # Sets fill style
    # 1 arg: HTML string value
    # 3 args: r, g, b are int between 0 and 255
    # 4 args: r, g, b, a, where r, g, b are ints between 0 and 255, and  a (alpha) is a float between 0 and 1.0
    def fill_style(self, *args):
        self.canvas.fill_style = self.parse_color("fill_style", *args)

    def stroke_style(self, *args):
        self.canvas.stroke_style = self.parse_color("stroke_style", *args)

    # Combines fill_rect and stroke_rect into one wrapper function
    def rect(self, *args):
        self.check_coords("rect", *args)
        
        self.canvas.fill_rect(*args)
        self.canvas.stroke_rect(*args)

    # Similar to self.rect wrapper, except only accepts x, y and size
    def square(self, *args):
        self.check_coords("square", *args, width_only=True)
        rect_args = (*args, args[2]) # Copy the width arg into the height
        self.rect(*rect_args)

    # Draws filled rect
    def fill_rect(self, *args):
        self.check_coords("fill_rect", *args)
        self.canvas.fill_rect(*args)
    
    # Strokes a rect
    def stroke_rect(self, *args):
        self.check_coords("stroke_rect", *args)
        self.canvas.stroke_rect(*args)

    #Clears a rect
    def clear_rect(self, *args):
        self.check_coords('clear_rect', *args)
        self.canvas.clear_rect(*args)

    # Draws circle at given coordinates
    def circle(self, *args):
        self.check_coords("circle", *args, width_only=True)
        arc_args = self.arc_args(*args)
        self.canvas.fill_arc(*arc_args)
        self.canvas.stroke_arc(*arc_args)

    # Draws filled circle
    def fill_circle(self, *args):
        self.check_coords("fill_circle", *args, width_only=True)
        arc_args = self.arc_args(*args)
        self.canvas.fill_arc(*arc_args)

    # Draws circle stroke
    def stroke_circle(self, *args):
        self.check_coords("stroke_circle", *args, width_only=True)
        arc_args = self.arc_args(*args)
        self.canvas.stroke_arc(*arc_args)
        
    def fill_arc(self, *args):
        self.canvas.fill_arc(*args)

    def stroke_arc(self, *args):
        self.canvas.stroke_arc(*args)
    
    def fill_text(self, *args):
        self.canvas.font = "{px}px sans-serif".format(px = args[4])
        self.canvas.fill_text(args[0:3])
        self.canvas.font = "12px sans-serif"

    def stroke_text(self, *args):
        self.canvas.font = "{px}px sans-serif".format(px = args[4])
        self.canvas.stroke_text(args[0:3])
        self.canvas.font = "12px sans-serif"

    def text_align(self, *args):
        self.canvas.text_align(*args)

    def draw_line(self, *args):
        if len(args) == 4:
            self.canvas.line_width = args[4]
        else:
            self.canvas.line_width = 1
            
        self.canvas.begin_path()
        self.canvas.move_to(args[0],args[1])
        self.canvas.line_to(args[2],args[4])
        self.canvas.close_path()

    # Clears canvas
    def clear(self, *args):
        self.canvas.clear()

    
    # Draws background on canvas
    def background(self, *args):
        old_fill = self.canvas.fill_style
        argc = len(args)

        if argc == 3:
            if ((not type(args[0]) is int) or (not type(args[1]) is int) or (not type(args[2]) is int)):
                raise TypeError("Enter Values between 0 and 255(integers only) for all 3 values")
            elif (not (args[0] >= 0 and args[0] <= 255) or not (args[1] >= 0 and args[1] <= 255) or not (
                args[2] >= 0 and args[2] <= 255)):
                raise TypeError("Enter Values between 0 and 255(integers only) for all 3 values")
            self.clear()
            self.fill_style(args[0], args[1], args[2])
            self.fill_rect(0, 0, self.width, self.height)
        elif argc == 1:
            if (not type(args[0]) is str):
                raise TypeError("Enter colour value in Hex i.e #000000 for black and so on")
            self.clear()
            self.fill_style(args[0])
            self.fill_rect(0, 0, self.width, self.height)
        elif argc == 4:
            if ((not type(args[0]) is int) or (not type(args[1]) is int) or (not type(args[2]) is int) or (
            not type(args[3]) is float)):
                raise TypeError("Enter Values between 0 and 255(integers only) for all 3 values")
            elif (not (args[0] >= 0 and args[0] <= 255) or not (args[1] >= 0 and args[1] <= 255) or not (
                args[2] >= 0 and args[2] <= 255) or not (args[3] >= 0.0 and args[3] <= 1.0)):
                raise TypeError(
                "Enter Values between 0 and 255(integers only) for all 3 values and a value between 0.0 and 1.0 for opacity(last argument")
            self.clear()
            self.fill_style(args[0], args[1], args[2], args[3])
            self.fill_rect(0, 0, self.width, self.height)
        
        self.canvas.fill_style = old_fill
    
    ### Helper Functions ###

    # Tests if input is numeric
    # Note: No support for complex numbers
    def check_type_is_num(self, n, func_name=None):
        if not isinstance(n, (int, float)):
            msg = "Expected {} to be a number".format(n)
            if func_name:
                msg = "{} expected {} to be a number".format(func_name, self.quote_if_string(n))
            raise TypeError(msg)

    # Tests if input is an int
    def check_type_is_int(self, n, func_name=None):
        if type(n) is not int:
            msg = "Expected {} to be an int".format(n)
            if func_name:
                msg = "{} expected {} to be an int".format(func_name, self.quote_if_string(n))
            raise TypeError(msg)

    # Tests if input is a float
    # allow_int: Set to True to allow ints as a float. Defaults to True.
    def check_type_is_float(self, n, func_name=None, allow_int=True):
        if type(n) is not float:
            if not allow_int or type(n) is not int:
                msg = "Expected {} to be a float".format(n)
                if func_name:
                    msg = "{} expected {} to be a float".format(func_name, self.quote_if_string(n))
                raise TypeError(msg)

    @staticmethod
    def quote_if_string(val):
        if type(val) is str:
            return "\"{}\"".format(val)
        else:
            return val
    
    # Parse a string, rgb or rgba input into an HTML color string
    def parse_color(self, func_name, *args):
        argc = len(args)

        if argc == 1:
            return args[0]
        elif argc == 3 or argc == 4:
            color_args = args[:3]
            for col in color_args:
                self.check_type_is_int(col, func_name)
            color_args = np.clip(color_args, 0, 255)

            if argc == 3:
                return "rgb({}, {}, {})".format(*color_args)
            else:
                # Clip alpha between 0 and 1
                alpha_arg = args[3]
                self.check_type_is_float(alpha_arg, func_name)
                alpha_arg = np.clip(alpha_arg, 0, 1.0)
                return "rgba({}, {}, {}, {})".format(*color_args, alpha_arg)
        else:
            raise TypeError("{} expected {}, {} or {} arguments, got {}".format(func_name, 1, 3, 4, argc))

    # Check a set of 4 args are valid coordinates
    # x, y, w, h
    def check_coords(self, func_name, *args, width_only=False):
        argc = len(args)
        if argc != 4 and not width_only:
            raise TypeError("{} expected {} arguments for x, y, w, h, got {} arguments".format(func_name, 4, argc))
        elif argc != 3 and width_only:
            raise TypeError("{} expected {} arguments for x, y, size, got {} arguments".format(func_name, 3, argc))

        for arg in args:
            self.check_type_is_float(arg, func_name)

    # Convert a tuple of circle args into arc args 
    def arc_args(self, *args):
        return (args[0], args[1], args[2] / 2, 0, 2 * pi)
Example #48
0
    def _make_repr_widget(self):
        button_refresh = Button(description='Refresh',
                                tooltip='Get representation info')
        button_update = Button(
            description='Update',
            tooltip='Update representation by updating rinfo box')
        button_remove = Button(description='Remove',
                               tooltip='Remove current representation')
        button_hide = Button(description='Hide',
                             tooltip='Hide/Show current representation')
        button_center_selection = Button(description='Center',
                                         tooltip='center selected atoms')
        button_center_selection._ngl_name = 'button_center_selection'

        bbox = HBox([
            button_refresh, button_center_selection, button_hide, button_remove
        ])

        repr_name_text = Text(value='', description='')
        repr_name_text._ngl_name = 'repr_name_text'
        repr_selection = Text(value='', description='')
        repr_selection._ngl_name = 'repr_selection'
        repr_selection.width = repr_name_text.width = DEFAULT_TEXT_WIDTH

        repr_info_box = VBox([repr_name_text, repr_selection])
        repr_info_box._ngl_name = 'repr_info_box'

        component_slider = IntSlider(value=0, description='component')
        component_slider._ngl_name = 'component_slider'
        component_slider.visible = False

        cvalue = ' '
        component_dropdown = Dropdown(value=cvalue,
                                      options=[
                                          cvalue,
                                      ],
                                      description='component')
        component_dropdown._ngl_name = 'component_dropdown'

        repr_slider = IntSlider(value=0,
                                description='representation',
                                width=DEFAULT_SLIDER_WIDTH)
        repr_slider._ngl_name = 'repr_slider'
        repr_slider.visible = True

        repr_text_info = Textarea(value='',
                                  description='representation parameters')
        repr_text_info.visible = False
        checkbox_repr_text = Checkbox(value=False,
                                      description='show parameters')
        checkbox_repr_text.visible = False
        repr_text_box = VBox([checkbox_repr_text, repr_text_info])
        repr_text_box._ngl_name = 'repr_text_box'

        checkbox_reprlist = Checkbox(value=False, description='reprlist')
        checkbox_reprlist._ngl_name = 'checkbox_reprlist'
        reprlist_choices = self._make_repr_name_choices(
            component_slider, repr_slider)
        reprlist_choices._ngl_name = 'reprlist_choices'

        def on_update_checkbox_reprlist(change):
            reprlist_choices.visible = change['new']

        checkbox_reprlist.observe(on_update_checkbox_reprlist, names='value')

        def on_click_refresh(button):
            self._view._request_repr_parameters(
                component=component_slider.value, repr_index=repr_slider.value)
            self._view._remote_call('requestReprInfo', target='Widget')

        button_refresh.on_click(on_click_refresh)

        def on_click_update(button):
            parameters = json.loads(
                repr_text_info.value.replace("False",
                                             "false").replace("True", "true"))
            self._view.update_representation(component=component_slider.value,
                                             repr_index=repr_slider.value,
                                             **parameters)
            self._view._set_selection(repr_selection.value,
                                      component=component_slider.value,
                                      repr_index=repr_slider.value)

        button_update.on_click(on_click_update)

        def on_click_remove(button_remove):
            self._view._remove_representation(component=component_slider.value,
                                              repr_index=repr_slider.value)
            self._view._request_repr_parameters(
                component=component_slider.value, repr_index=repr_slider.value)

        button_remove.on_click(on_click_remove)

        def on_click_hide(button_hide):
            component = component_slider.value
            repr_index = repr_slider.value

            if button_hide.description == 'Hide':
                hide = True
                button_hide.description = 'Show'
            elif button_hide.description == 'Show':
                hide = False
                button_hide.description = 'Hide'
            else:
                raise ValueError("must be Hide or Show")

            self._view._remote_call('setVisibilityForRepr',
                                    target='Widget',
                                    args=[component, repr_index, not hide])

        button_hide.on_click(on_click_hide)

        def on_click_center(center_selection):
            self._view.center_view(selection=repr_selection.value,
                                   component=component_slider.value)

        button_center_selection.on_click(on_click_center)

        def on_change_repr_name(change):
            name = change['new'].strip()
            old = change['old'].strip()

            should_update = (self._real_time_update and old and name
                             and name in REPR_NAMES
                             and name != change['old'].strip())

            if should_update:
                component = component_slider.value
                repr_index = repr_slider.value
                self._view._remote_call(
                    'setRepresentation',
                    target='Widget',
                    args=[change['new'], {}, component, repr_index])
                self._view._request_repr_parameters(component, repr_index)

        def update_slider_info(change):
            self._view._request_repr_parameters(
                component=component_slider.value, repr_index=repr_slider.value)
            component_dropdown.options = tuple(self._view._ngl_component_names)

        def on_change_selection(change):
            if self._real_time_update:
                component = component_slider.value
                repr_index = repr_slider.value
                self._view._set_selection(change['new'],
                                          component=component,
                                          repr_index=repr_index)

        def on_change_component_dropdown(change):
            choice = change['new']
            if choice:
                component_slider.value = self._view._ngl_component_names.index(
                    choice)

        component_dropdown.observe(on_change_component_dropdown, names='value')

        def on_change_checkbox_repr_text(change):
            repr_text_info.visible = change['new']

        repr_slider.observe(update_slider_info, names='value')
        component_slider.observe(update_slider_info, names='value')
        repr_name_text.observe(on_change_repr_name, names='value')
        repr_selection.observe(on_change_selection, names='value')
        checkbox_repr_text.observe(on_change_checkbox_repr_text, names='value')

        # HC
        repr_parameters_box = self._make_repr_parameter_slider()
        repr_parameters_box._ngl_name = 'repr_parameters_box'

        # NOTE: if you update below list, make sure to update _make_repr_parameter_slider
        # or refactor
        # try to "refresh"
        vbox = VBox([
            component_dropdown, bbox, repr_info_box, component_slider,
            repr_slider, reprlist_choices, repr_text_box, repr_parameters_box
        ])
        self._view._request_repr_parameters(component=component_slider.value,
                                            repr_index=repr_slider.value)
        return vbox
Example #49
0
PARADIM_UI = {}
PARADIM_UI['s0'] = {}
PARADIM_UI['s0']['pwd'] = MyPassword(description='MARCC Password',
                                     name='MARCC Password',
                                     value=PARADIM['PWD'])
PARADIM_UI['s0']['code'] = ui.String(description='GOOGLE AUTH Code',
                                     name='GOOGLE AUTH Code',
                                     value=PARADIM['CODE'])
PARADIM_UI['s0']['user'] = ui.String(description='Marcc User name',
                                     name='Marcc User name',
                                     value=PARADIM['USER'])
PARADIM_UI['s0']['folder'] = ui.String(description='Working folder',
                                       name='Working folder',
                                       value=PARADIM['TUTORIAL_NAME'])

PARADIM_UI['s0']['button'] = Button(description='Connect')
PARADIM_UI['s0']['button'].w = Box([PARADIM_UI['s0']['button']])
PARADIM_UI['s0']['status'] = ui.String(name='Status',
                                       description='Status',
                                       value='')
PARADIM_UI['s0']['status'].dd.layout = Layout(width='100%')
PARADIM_UI['s0']['status'].disabled = True
PARADIM_UI['s0']['display'] = ui.Form([
    PARADIM_UI['s0']['user'],
    PARADIM_UI['s0']['pwd'],
    PARADIM_UI['s0']['code'],
    PARADIM_UI['s0']['folder'],
    PARADIM_UI['s0']['button'],
    PARADIM_UI['s0']['status'],
],
                                      name='MARCC Credentials')
Example #50
0
    def interactive_classifier(self, data_types=('expression', 'splicing'),
                               sample_subsets=None,
                               feature_subsets=None,
                               categorical_variables=None,
                               predictor_types=None,
                               score_coefficient=(0.1, 20),
                               draw_labels=False):

        def do_interact(data_type,
                        sample_subset,
                        feature_subset,
                        predictor_type=default_classifier,
                        categorical_variable='outlier',
                        score_coefficient=2,
                        plot_violins=False,
                        show_point_labels=False):

            for k, v in locals().iteritems():
                if k == 'self':
                    continue
                sys.stdout.write('{} : {}\n'.format(k, v))

            self.plot_classifier(trait=categorical_variable,
                                 feature_subset=feature_subset,
                                 sample_subset=sample_subset,
                                 predictor_name=predictor_type,
                                 score_coefficient=score_coefficient,
                                 data_type=data_type,
                                 plot_violins=plot_violins,
                                 show_point_labels=show_point_labels)

        if feature_subsets is None:
            feature_subsets = Interactive.get_feature_subsets(self, data_types)
            feature_subsets.insert(0, 'variant')
        if sample_subsets is None:
            sample_subsets = self.default_sample_subsets

        if categorical_variables is None:
            categorical_variables = [i for i in self.default_sample_subsets if
                                     not i.startswith(
                                         "~") and i != 'all_samples']

        if predictor_types is None:
            predictor_types = \
                self.predictor_config_manager.predictor_configs.keys()

        # self.plot_study_sample_legend()

        gui = interact(do_interact,
                       data_type=data_types,
                       sample_subset=sample_subsets,
                       feature_subset=feature_subsets,
                       categorical_variable=categorical_variables,
                       score_coefficient=score_coefficient,
                       draw_labels=draw_labels,
                       predictor_type=predictor_types)

        def save(w):
            # Make the directory if it's not already there
            filename, extension = os.path.splitext(savefile.value)
            self.maybe_make_directory(savefile.value)

            gui.widget.result.fig_reduced.savefig(savefile.value,
                                                  format=extension)

            # add "violins" after the provided filename, but before the
            # extension
            violins_file = '{}.{}'.format("_".join([filename, 'violins']),
                                          extension)
            try:
                gui.widget.result.fig_violins.savefig(
                    violins_file, format=extension.lstrip('.'))
            except AttributeError:
                pass

        savefile = Text(description='savefile')
        save_widget = Button(description='save')
        gui.widget.children = list(gui.widget.children) + [savefile,
                                                           save_widget]
        save_widget.on_click(save)
        return gui
Example #51
0
class Dashboard(VBox):
    """
    Build the dashboard for Jupyter widgets. Requires running
    in a notebook/jupyterlab.
    """
    def __init__(self, net, width="95%", height="550px", play_rate=0.5):
        self._ignore_layer_updates = False
        self.player = _Player(self, play_rate)
        self.player.start()
        self.net = net
        r = random.randint(1, 1000000)
        self.class_id = "picture-dashboard-%s-%s" % (self.net.name, r)
        self._width = width
        self._height = height
        ## Global widgets:
        style = {"description_width": "initial"}
        self.feature_columns = IntText(description="Detail columns:",
                                       value=self.net.config["dashboard.features.columns"],
                                       min=0,
                                       max=1024,
                                       style=style)
        self.feature_scale = FloatText(description="Detail scale:",
                                       value=self.net.config["dashboard.features.scale"],
                                       min=0.1,
                                       max=10,
                                       style=style)
        self.feature_columns.observe(self.regenerate, names='value')
        self.feature_scale.observe(self.regenerate, names='value')
        ## Hack to center SVG as justify-content is broken:
        self.net_svg = HTML(value="""<p style="text-align:center">%s</p>""" % ("",), layout=Layout(
            width=self._width, overflow_x='auto', overflow_y="auto",
            justify_content="center"))
        # Make controls first:
        self.output = Output()
        controls = self.make_controls()
        config = self.make_config()
        super().__init__([config, controls, self.net_svg, self.output])

    def propagate(self, inputs):
        """
        Propagate inputs through the dashboard view of the network.
        """
        if dynamic_pictures_check():
            return self.net.propagate(inputs, class_id=self.class_id, update_pictures=True)
        else:
            self.regenerate(inputs=input)

    def goto(self, position):
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            return
        if self.control_select.value == "Train":
            length = len(self.net.dataset.train_inputs)
        elif self.control_select.value == "Test":
            length = len(self.net.dataset.test_inputs)
        #### Position it:
        if position == "begin":
            self.control_slider.value = 0
        elif position == "end":
            self.control_slider.value = length - 1
        elif position == "prev":
            if self.control_slider.value - 1 < 0:
                self.control_slider.value = length - 1 # wrap around
            else:
                self.control_slider.value = max(self.control_slider.value - 1, 0)
        elif position == "next":
            if self.control_slider.value + 1 > length - 1:
                self.control_slider.value = 0 # wrap around
            else:
                self.control_slider.value = min(self.control_slider.value + 1, length - 1)
        self.position_text.value = self.control_slider.value


    def change_select(self, change=None):
        """
        """
        self.update_control_slider(change)
        self.regenerate()

    def update_control_slider(self, change=None):
        self.net.config["dashboard.dataset"] = self.control_select.value
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            self.total_text.value = "of 0"
            self.control_slider.value = 0
            self.position_text.value = 0
            self.control_slider.disabled = True
            self.position_text.disabled = True
            for child in self.control_buttons.children:
                if not hasattr(child, "icon") or child.icon != "refresh":
                    child.disabled = True
            return
        if self.control_select.value == "Test":
            self.total_text.value = "of %s" % len(self.net.dataset.test_inputs)
            minmax = (0, max(len(self.net.dataset.test_inputs) - 1, 0))
            if minmax[0] <= self.control_slider.value <= minmax[1]:
                pass # ok
            else:
                self.control_slider.value = 0
            self.control_slider.min = minmax[0]
            self.control_slider.max = minmax[1]
            if len(self.net.dataset.test_inputs) == 0:
                disabled = True
            else:
                disabled = False
        elif self.control_select.value == "Train":
            self.total_text.value = "of %s" % len(self.net.dataset.train_inputs)
            minmax = (0, max(len(self.net.dataset.train_inputs) - 1, 0))
            if minmax[0] <= self.control_slider.value <= minmax[1]:
                pass # ok
            else:
                self.control_slider.value = 0
            self.control_slider.min = minmax[0]
            self.control_slider.max = minmax[1]
            if len(self.net.dataset.train_inputs) == 0:
                disabled = True
            else:
                disabled = False
        self.control_slider.disabled = disabled
        self.position_text.disbaled = disabled
        self.position_text.value = self.control_slider.value
        for child in self.control_buttons.children:
            if not hasattr(child, "icon") or child.icon != "refresh":
                child.disabled = disabled

    def update_zoom_slider(self, change):
        if change["name"] == "value":
            self.net.config["svg_scale"] = self.zoom_slider.value
            self.regenerate()

    def update_position_text(self, change):
        # {'name': 'value', 'old': 2, 'new': 3, 'owner': IntText(value=3, layout=Layout(width='100%')), 'type': 'change'}
        self.control_slider.value = change["new"]

    def get_current_input(self):
        if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
            return self.net.dataset.train_inputs[self.control_slider.value]
        elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
            return self.net.dataset.test_inputs[self.control_slider.value]

    def get_current_targets(self):
        if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
            return self.net.dataset.train_targets[self.control_slider.value]
        elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
            return self.net.dataset.test_targets[self.control_slider.value]

    def update_slider_control(self, change):
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            self.total_text.value = "of 0"
            return
        if change["name"] == "value":
            self.position_text.value = self.control_slider.value
            if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
                self.total_text.value = "of %s" % len(self.net.dataset.train_inputs)
                if self.net.model is None:
                    return
                if not dynamic_pictures_check():
                    self.regenerate(inputs=self.net.dataset.train_inputs[self.control_slider.value],
                                    targets=self.net.dataset.train_targets[self.control_slider.value])
                    return
                output = self.net.propagate(self.net.dataset.train_inputs[self.control_slider.value],
                                            class_id=self.class_id, update_pictures=True)
                if self.feature_bank.value in self.net.layer_dict.keys():
                    self.net.propagate_to_features(self.feature_bank.value, self.net.dataset.train_inputs[self.control_slider.value],
                                                   cols=self.feature_columns.value, scale=self.feature_scale.value, html=False)
                if self.net.config["show_targets"]:
                    if len(self.net.output_bank_order) == 1: ## FIXME: use minmax of output bank
                        self.net.display_component([self.net.dataset.train_targets[self.control_slider.value]],
                                                   "targets",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        self.net.display_component(self.net.dataset.train_targets[self.control_slider.value],
                                                   "targets",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                if self.net.config["show_errors"]: ## minmax is error
                    if len(self.net.output_bank_order) == 1:
                        errors = np.array(output) - np.array(self.net.dataset.train_targets[self.control_slider.value])
                        self.net.display_component([errors.tolist()],
                                                   "errors",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        errors = []
                        for bank in range(len(self.net.output_bank_order)):
                            errors.append( np.array(output[bank]) - np.array(self.net.dataset.train_targets[self.control_slider.value][bank]))
                        self.net.display_component(errors, "errors",  class_id=self.class_id, minmax=(-1, 1))
            elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
                self.total_text.value = "of %s" % len(self.net.dataset.test_inputs)
                if self.net.model is None:
                    return
                if not dynamic_pictures_check():
                    self.regenerate(inputs=self.net.dataset.test_inputs[self.control_slider.value],
                                    targets=self.net.dataset.test_targets[self.control_slider.value])
                    return
                output = self.net.propagate(self.net.dataset.test_inputs[self.control_slider.value],
                                            class_id=self.class_id, update_pictures=True)
                if self.feature_bank.value in self.net.layer_dict.keys():
                    self.net.propagate_to_features(self.feature_bank.value, self.net.dataset.test_inputs[self.control_slider.value],
                                               cols=self.feature_columns.value, scale=self.feature_scale.value, html=False)
                if self.net.config["show_targets"]: ## FIXME: use minmax of output bank
                    self.net.display_component([self.net.dataset.test_targets[self.control_slider.value]],
                                               "targets",
                                               class_id=self.class_id,
                                               minmax=(-1, 1))
                if self.net.config["show_errors"]: ## minmax is error
                    if len(self.net.output_bank_order) == 1:
                        errors = np.array(output) - np.array(self.net.dataset.test_targets[self.control_slider.value])
                        self.net.display_component([errors.tolist()],
                                                   "errors",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        errors = []
                        for bank in range(len(self.net.output_bank_order)):
                            errors.append( np.array(output[bank]) - np.array(self.net.dataset.test_targets[self.control_slider.value][bank]))
                        self.net.display_component(errors, "errors", class_id=self.class_id, minmax=(-1, 1))

    def toggle_play(self, button):
        ## toggle
        if self.button_play.description == "Play":
            self.button_play.description = "Stop"
            self.button_play.icon = "pause"
            self.player.resume()
        else:
            self.button_play.description = "Play"
            self.button_play.icon = "play"
            self.player.pause()

    def prop_one(self, button=None):
        self.update_slider_control({"name": "value"})

    def regenerate(self, button=None, inputs=None, targets=None):
        ## Protection when deleting object on shutdown:
        if isinstance(button, dict) and 'new' in button and button['new'] is None:
            return
        ## Update the config:
        self.net.config["dashboard.features.bank"] = self.feature_bank.value
        self.net.config["dashboard.features.columns"] = self.feature_columns.value
        self.net.config["dashboard.features.scale"] = self.feature_scale.value
        inputs = inputs if inputs is not None else self.get_current_input()
        targets = targets if targets is not None else self.get_current_targets()
        features = None
        if self.feature_bank.value in self.net.layer_dict.keys() and inputs is not None:
            if self.net.model is not None:
                features = self.net.propagate_to_features(self.feature_bank.value, inputs,
                                                          cols=self.feature_columns.value,
                                                          scale=self.feature_scale.value, display=False)
        svg = """<p style="text-align:center">%s</p>""" % (self.net.to_svg(
            inputs=inputs,
            targets=targets,
            class_id=self.class_id,
            highlights={self.feature_bank.value: {
                "border_color": "orange",
                "border_width": 30,
            }}))
        if inputs is not None and features is not None:
            html_horizontal = """
<table align="center" style="width: 100%%;">
 <tr>
  <td valign="top" style="width: 50%%;">%s</td>
  <td valign="top" align="center" style="width: 50%%;"><p style="text-align:center"><b>%s</b></p>%s</td>
</tr>
</table>"""
            html_vertical = """
<table align="center" style="width: 100%%;">
 <tr>
  <td valign="top">%s</td>
</tr>
<tr>
  <td valign="top" align="center"><p style="text-align:center"><b>%s</b></p>%s</td>
</tr>
</table>"""
            self.net_svg.value = (html_vertical if self.net.config["svg_rotate"] else html_horizontal) % (
                svg, "%s details" % self.feature_bank.value, features)
        else:
            self.net_svg.value = svg

    def make_colormap_image(self, colormap_name):
        from .layers import Layer
        if not colormap_name:
            colormap_name = get_colormap()
        layer = Layer("Colormap", 100)
        minmax = layer.get_act_minmax()
        image = layer.make_image(np.arange(minmax[0], minmax[1], .01),
                                 colormap_name,
                                 {"pixels_per_unit": 1,
                                  "svg_rotate": self.net.config["svg_rotate"]}).resize((300, 25))
        return image

    def set_attr(self, obj, attr, value):
        if value not in [{}, None]: ## value is None when shutting down
            if isinstance(value, dict):
                value = value["value"]
            if isinstance(obj, dict):
                obj[attr] = value
            else:
                setattr(obj, attr, value)
            ## was crashing on Widgets.__del__, if get_ipython() no longer existed
            self.regenerate()

    def make_controls(self):
        layout = Layout(width='100%', height="100%")
        button_begin = Button(icon="fast-backward", layout=layout)
        button_prev = Button(icon="backward", layout=layout)
        button_next = Button(icon="forward", layout=layout)
        button_end = Button(icon="fast-forward", layout=layout)
        #button_prop = Button(description="Propagate", layout=Layout(width='100%'))
        #button_train = Button(description="Train", layout=Layout(width='100%'))
        self.button_play = Button(icon="play", description="Play", layout=layout)
        step_down = Button(icon="sort-down", layout=Layout(width="95%", height="100%"))
        step_up = Button(icon="sort-up", layout=Layout(width="95%", height="100%"))
        up_down = HBox([step_down, step_up], layout=Layout(width="100%", height="100%"))
        refresh_button = Button(icon="refresh", layout=Layout(width="25%", height="100%"))

        self.position_text = IntText(value=0, layout=layout)

        self.control_buttons = HBox([
            button_begin,
            button_prev,
            #button_train,
            self.position_text,
            button_next,
            button_end,
            self.button_play,
            up_down,
            refresh_button
        ], layout=Layout(width='100%', height="100%"))
        length = (len(self.net.dataset.train_inputs) - 1) if len(self.net.dataset.train_inputs) > 0 else 0
        self.control_slider = IntSlider(description="Dataset index",
                                   continuous_update=False,
                                   min=0,
                                   max=max(length, 0),
                                   value=0,
                                   layout=Layout(width='100%'))
        if self.net.config["dashboard.dataset"] == "Train":
            length = len(self.net.dataset.train_inputs)
        else:
            length = len(self.net.dataset.test_inputs)
        self.total_text = Label(value="of %s" % length, layout=Layout(width="100px"))
        self.zoom_slider = FloatSlider(description="Zoom",
                                       continuous_update=False,
                                       min=0, max=1.0,
                                       style={"description_width": 'initial'},
                                       layout=Layout(width="65%"),
                                       value=self.net.config["svg_scale"] if self.net.config["svg_scale"] is not None else 0.5)

        ## Hook them up:
        button_begin.on_click(lambda button: self.goto("begin"))
        button_end.on_click(lambda button: self.goto("end"))
        button_next.on_click(lambda button: self.goto("next"))
        button_prev.on_click(lambda button: self.goto("prev"))
        self.button_play.on_click(self.toggle_play)
        self.control_slider.observe(self.update_slider_control, names='value')
        refresh_button.on_click(lambda widget: (self.update_control_slider(),
                                                self.output.clear_output(),
                                                self.regenerate()))
        step_down.on_click(lambda widget: self.move_step("down"))
        step_up.on_click(lambda widget: self.move_step("up"))
        self.zoom_slider.observe(self.update_zoom_slider, names='value')
        self.position_text.observe(self.update_position_text, names='value')
        # Put them together:
        controls = VBox([HBox([self.control_slider, self.total_text], layout=Layout(height="40px")),
                         self.control_buttons], layout=Layout(width='100%'))

        #net_page = VBox([control, self.net_svg], layout=Layout(width='95%'))
        controls.on_displayed(lambda widget: self.regenerate())
        return controls

    def move_step(self, direction):
        """
        Move the layer stepper up/down through network
        """
        options = [""] + [layer.name for layer in self.net.layers]
        index = options.index(self.feature_bank.value)
        if direction == "up":
            new_index = (index + 1) % len(options)
        else: ## down
            new_index = (index - 1) % len(options)
        self.feature_bank.value = options[new_index]
        self.regenerate()

    def make_config(self):
        layout = Layout()
        style = {"description_width": "initial"}
        checkbox1 = Checkbox(description="Show Targets", value=self.net.config["show_targets"],
                             layout=layout, style=style)
        checkbox1.observe(lambda change: self.set_attr(self.net.config, "show_targets", change["new"]), names='value')
        checkbox2 = Checkbox(description="Errors", value=self.net.config["show_errors"],
                             layout=layout, style=style)
        checkbox2.observe(lambda change: self.set_attr(self.net.config, "show_errors", change["new"]), names='value')

        hspace = IntText(value=self.net.config["hspace"], description="Horizontal space between banks:",
                         style=style, layout=layout)
        hspace.observe(lambda change: self.set_attr(self.net.config, "hspace", change["new"]), names='value')
        vspace = IntText(value=self.net.config["vspace"], description="Vertical space between layers:",
                         style=style, layout=layout)
        vspace.observe(lambda change: self.set_attr(self.net.config, "vspace", change["new"]), names='value')
        self.feature_bank = Select(description="Details:", value=self.net.config["dashboard.features.bank"],
                              options=[""] + [layer.name for layer in self.net.layers],
                              rows=1)
        self.feature_bank.observe(self.regenerate, names='value')
        self.control_select = Select(
            options=['Test', 'Train'],
            value=self.net.config["dashboard.dataset"],
            description='Dataset:',
            rows=1
        )
        self.control_select.observe(self.change_select, names='value')
        column1 = [self.control_select,
                   self.zoom_slider,
                   hspace,
                   vspace,
                   HBox([checkbox1, checkbox2]),
                   self.feature_bank,
                   self.feature_columns,
                   self.feature_scale
        ]
        ## Make layer selectable, and update-able:
        column2 = []
        layer = self.net.layers[-1]
        self.layer_select = Select(description="Layer:", value=layer.name,
                                   options=[layer.name for layer in
                                            self.net.layers],
                                   rows=1)
        self.layer_select.observe(self.update_layer_selection, names='value')
        column2.append(self.layer_select)
        self.layer_visible_checkbox = Checkbox(description="Visible", value=layer.visible, layout=layout)
        self.layer_visible_checkbox.observe(self.update_layer, names='value')
        column2.append(self.layer_visible_checkbox)
        self.layer_colormap = Select(description="Colormap:",
                                     options=[""] + AVAILABLE_COLORMAPS,
                                     value=layer.colormap if layer.colormap is not None else "", layout=layout, rows=1)
        self.layer_colormap_image = HTML(value="""<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap)))
        self.layer_colormap.observe(self.update_layer, names='value')
        column2.append(self.layer_colormap)
        column2.append(self.layer_colormap_image)
        ## get dynamic minmax; if you change it it will set it in layer as override:
        minmax = layer.get_act_minmax()
        self.layer_mindim = FloatText(description="Leftmost color maps to:", value=minmax[0], style=style)
        self.layer_maxdim = FloatText(description="Rightmost color maps to:", value=minmax[1], style=style)
        self.layer_mindim.observe(self.update_layer, names='value')
        self.layer_maxdim.observe(self.update_layer, names='value')
        column2.append(self.layer_mindim)
        column2.append(self.layer_maxdim)
        output_shape = layer.get_output_shape()
        self.layer_feature = IntText(value=layer.feature, description="Feature to show:", style=style)
        self.svg_rotate = Checkbox(description="Rotate", value=layer.visible, layout=layout)
        self.layer_feature.observe(self.update_layer, names='value')
        column2.append(self.layer_feature)
        self.svg_rotate = Checkbox(description="Rotate network",
                                   value=self.net.config["svg_rotate"],
                                   style={"description_width": 'initial'},
                                   layout=Layout(width="52%"))
        self.svg_rotate.observe(lambda change: self.set_attr(self.net.config, "svg_rotate", change["new"]), names='value')
        self.save_config_button = Button(icon="save", layout=Layout(width="10%"))
        self.save_config_button.on_click(self.save_config)
        column2.append(HBox([self.svg_rotate, self.save_config_button]))
        config_children = HBox([VBox(column1, layout=Layout(width="100%")),
                                VBox(column2, layout=Layout(width="100%"))])
        accordion = Accordion(children=[config_children])
        accordion.set_title(0, self.net.name)
        accordion.selected_index = None
        return accordion

    def save_config(self, widget=None):
        self.net.save_config()

    def update_layer(self, change):
        """
        Update the layer object, and redisplay.
        """
        if self._ignore_layer_updates:
            return
        ## The rest indicates a change to a display variable.
        ## We need to save the value in the layer, and regenerate
        ## the display.
        # Get the layer:
        layer = self.net[self.layer_select.value]
        # Save the changed value in the layer:
        layer.feature = self.layer_feature.value
        layer.visible = self.layer_visible_checkbox.value
        ## These three, dealing with colors of activations,
        ## can be done with a prop_one():
        if "color" in change["owner"].description.lower():
            ## Matches: Colormap, lefmost color, rightmost color
            ## overriding dynamic minmax!
            layer.minmax = (self.layer_mindim.value, self.layer_maxdim.value)
            layer.minmax = (self.layer_mindim.value, self.layer_maxdim.value)
            layer.colormap = self.layer_colormap.value if self.layer_colormap.value else None
            self.layer_colormap_image.value = """<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap))
            self.prop_one()
        else:
            self.regenerate()

    def update_layer_selection(self, change):
        """
        Just update the widgets; don't redraw anything.
        """
        ## No need to redisplay anything
        self._ignore_layer_updates = True
        ## First, get the new layer selected:
        layer = self.net[self.layer_select.value]
        ## Now, let's update all of the values without updating:
        self.layer_visible_checkbox.value = layer.visible
        self.layer_colormap.value = layer.colormap if layer.colormap != "" else ""
        self.layer_colormap_image.value = """<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap))
        minmax = layer.get_act_minmax()
        self.layer_mindim.value = minmax[0]
        self.layer_maxdim.value = minmax[1]
        self.layer_feature.value = layer.feature
        self._ignore_layer_updates = False
Example #52
0
    def interactive_pca(self, data_types=('expression', 'splicing'),
                        sample_subsets=None,
                        feature_subsets=None,
                        color_samples_by=None,
                        featurewise=False,
                        x_pc=(1, 10), y_pc=(1, 10),
                        show_point_labels=False,
                        list_link='', plot_violins=False,
                        scale_by_variance=True,
                        savefile='figures/last.pca.pdf'):

        def do_interact(data_type='expression',
                        sample_subset=self.default_sample_subsets,
                        feature_subset=self.default_feature_subsets,
                        featurewise=False,
                        list_link='',
                        x_pc=1, y_pc=2,
                        plot_violins=False,
                        show_point_labels=False,
                        color_samples_by=self.metadata.phenotype_col,
                        bokeh=False,
                        scale_by_variance=True,
                        most_variant_features=False,
                        std_multiplier=(0, 5.0)):
            for k, v in locals().iteritems():
                if k == 'self':
                    continue
                sys.stdout.write('{} : {}\n'.format(k, v))

            if feature_subset != "custom" and list_link != "":
                raise ValueError(
                    "Set feature_subset to \"custom\" to use list_link")

            if feature_subset == "custom" and list_link == "":
                raise ValueError("Use a custom list name please")

            if feature_subset == 'custom':
                feature_subset = link_to_list(list_link)

            elif feature_subset not in self.default_feature_subsets[data_type]:
                warnings.warn("This feature_subset ('{}') is not available in "
                              "this data type ('{}'). Falling back on all "

                              "features.".format(feature_subset, data_type))

            return self.plot_pca(sample_subset=sample_subset,
                                 data_type=data_type,
                                 featurewise=featurewise,
                                 x_pc=x_pc, y_pc=y_pc,
                                 show_point_labels=show_point_labels,
                                 feature_subset=feature_subset,
                                 plot_violins=plot_violins,
                                 color_samples_by=color_samples_by,
                                 bokeh=bokeh, std_multiplier=std_multiplier,
                                 scale_by_variance=scale_by_variance,
                                 most_variant_features=most_variant_features)

        # self.plot_study_sample_legend()

        if feature_subsets is None:
            feature_subsets = Interactive.get_feature_subsets(self, data_types)

        if sample_subsets is None:
            sample_subsets = self.default_sample_subsets

        color_samples_by = self.metadata.data.columns.tolist()

        gui = interact(do_interact,
                       data_type=data_types,
                       sample_subset=sample_subsets,
                       feature_subset=feature_subsets + ['custom'],
                       featurewise=featurewise,
                       x_pc=x_pc, y_pc=y_pc,
                       show_point_labels=show_point_labels,
                       list_link=list_link, plot_violins=plot_violins,
                       color_samples_by=color_samples_by,
                       scale_by_variance=scale_by_variance)

        def save(w):
            # Make the directory if it's not already there
            filename, extension = os.path.splitext(savefile.value)
            self.maybe_make_directory(savefile.value)

            gui.widget.result.fig_reduced.savefig(savefile.value,
                                                  format=extension)

            # add "violins" after the provided filename, but before the
            # extension
            violins_file = '{}.{}'.format("_".join([filename, 'violins']),
                                          extension)
            try:
                gui.widget.result.fig_violins.savefig(
                    violins_file, format=extension.lstrip('.'))
            except AttributeError:
                pass

        savefile = Text(description='savefile')
        save_widget = Button(description='save')
        gui.widget.children = list(gui.widget.children) + [savefile,
                                                           save_widget]
        save_widget.on_click(save)
        return gui
Example #53
0
class Dbfs(object):
    """Database browser implementation

    Args:
        dbutils (DBUtils): DBUtils object (for fs only)
    """
    def __init__(self, dbutils):
        self.dbutils = dbutils
        self.running = False

    def create(self, rows=30, path="/", height="400px"):
        if self.running:
            print("dbfs browser already running. Use close() first")
            return
        self.path = path
        self.flist = Select(options=[],
                            disabled=False,
                            layout={"height": height})
        self.flist.observe(self.on_click, names="value")

        self.refresh = Button(icon="refresh", layout={"width": "40px"})
        self.refresh.on_click(self.on_refresh)
        self.path_view = Output()
        self.preview = Output(
            layout={
                "width": "800px",
                "height": height,
                "overflow": "scroll",
                "border": "1px solid gray",
            })

        self.up = Button(icon="arrow-up", layout={"width": "40px"})
        self.up.on_click(self.on_up)

        display(
            VBox([
                HBox([self.refresh, self.up, self.path_view]),
                HBox([self.flist, self.preview]),
            ]))

        self.update()
        self.running = True

    def convertBytes(self, fsize):
        """Convert bytes to largest unit

        Args:
            fsize (int): Size in bytes

        Returns:
            tuple: size of largest unit, largest unit
        """
        size = fsize
        unit = "B"
        if size > 1024 * 1024 * 1024 * 10:
            size = int(size / 1024.0 / 1024.0 / 1024.0)
            unit = "GB"
        elif size > 1024 * 1024 * 10:
            size = int(size / 1024.0 / 1024.0)
            unit = "MB"
        elif size > 1024 * 10:
            size = int(size / 1024.0)
            unit = "KB"
        return (size, unit)

    def update(self):
        """Update the view when an element was selected"""
        self.path_view.clear_output()
        self.preview.clear_output()
        with self.path_view:
            print("updating ...")
        try:
            fobjs = self.dbutils.fs.ls(self.path)
        except Exception as ex:
            with self.path_view:
                print("Error: Cannot access folder")
            return False

        self.show_path(self.path)

        dirs = sorted([fobj.name for fobj in fobjs if fobj.isDir()],
                      key=lambda x: x.lower())
        files = sorted(
            [
                "%s (%d %s)" % ((fobj.name, ) + self.convertBytes(fobj.size))
                for fobj in fobjs if not fobj.isDir()
            ],
            key=lambda x: x[0].lower(),
        )
        self.flist.options = [""] + dirs + files
        return True

    def show_path(self, path):
        """Show path in output widget

        Args:
            path (str): Currently selected path
        """
        self.path_view.clear_output()
        with self.path_view:
            print("dbfs:" + re.sub(r"\s\(.*?\)$", "", path))

    def show_preview(self, path):
        """Show preview of csv, md or txt in output widget

        Args:
            path (str): Currently selected path
        """
        real_path = re.sub(r"\s\(.*?\)$", "", path)
        parts = real_path.split(".")
        if len(parts) > 0 and parts[-1].lower() in [
                "md",
                "html",
                "csv",
                "txt",
                "sh",
                "sql",
                "py",
                "scala",
                "json",
                "jpg",
                "jpeg",
                "png",
                "gif",
        ]:
            ext = parts[-1].lower()
            filename = "/dbfs" + real_path
            # text = self.dbutils.fs.head(real_path)
            self.preview.clear_output()
            with self.preview:
                if ext == "html":
                    display(HTML(filename=filename))
                elif ext in ["py", "sh", "sql", "scala"]:
                    display(Code(filename=filename))
                elif ext in ["jpg", "jpeg", "png", "gif"]:
                    display(Image(filename=filename))
                elif ext == "md":
                    display(Markdown(filename=filename))
                elif ext == "csv":
                    df = pd.read_csv(filename)
                    display(df)
                else:
                    with open(filename, "r") as fd:
                        print(fd.read())

    def on_refresh(self, b):
        """Refresh handler

        Args:
            b (ipywidgets.Button): clicked button
        """
        self.update()

    def on_up(self, b):
        """Up handler

        Args:
            b (ipywidgets.Button): clicked button
        """
        new_path = os.path.dirname(self.path.rstrip("/"))
        if new_path != self.path:
            self.path = new_path
        self.update()

    def on_click(self, change):
        """Click handler providing db and parent as context

        Args:
            db (str): database name
            parent (object): parent object
        """
        new_path = os.path.join(self.path, change["new"])
        if change["old"] is not None:
            if len(change["new"]) > 0 and change["new"][-1] == "/":
                old_path = self.path
                self.path = new_path
                if not self.update():
                    self.path = old_path
            else:
                self.show_path(new_path)
                self.show_preview(new_path)

    def close(self):
        """Close view"""
        self.running = False
    def compute(self):
        obj = self.value
        self.titlebox = ExplorerTitle(obj)
        self.description = ExplorerDescription(obj)
        self.props = ExplorerProperties(obj)
        def handle_click(e):
            self.set_value(e.source.value)
        for v in self.props.children:
            if type(v) == ExplorableValue:
                v.clc.on_dom_event(handle_click)
        self.propsbox = VBox([self.description, self.props])
        self.titlebox.add_class('titlebox')
        self.titlebox.add_class('lightborder')
        self.visualbox = ExplorerVisual(obj)
        self.visualbox.add_class('visualbox')

        self.top = VBox(
            [self.titlebox,
             HBox(
                 [self.propsbox, Separator(' '), self.visualbox],
                         layout=Layout(margin='10px 0')
             )
            ],
            layout=Layout(border='1px solid yellow')
        )

        self.menusbox = ExplorerMenus(obj)
        self.namingbox = ExplorerNaming(obj)
        self.searchbox = ExplorerMethodSearch(obj)
        self.inputbox = Text()
        self.inputbutton = Button(description='-', layout=Layout(width='30px'))
        self.gobutton = Button(description='Run!', tooltip='Run the method with specified arguments')
        def compute_selected_method(button):
            args = []
            if self.inputbox.value:
                args = self.inputbox.value.split(',')
            try:
            #    if AlarmInterrupt:
            #        alarm(TIMEOUT)
                out = self.searchbox.get_member()(obj, *args)
            #        if AlarmInterrupt:
            #            cancel_alarm()
            #except AlarmInterrupt:
            #    self.output.value = to_html("Timeout!")
            except Exception as e:
                self.outputbox.output.value = 'Error: %s; input=%s' % (e, str(args))
                return
            self.outputbox.output.value = '$%s$' % out
        self.gobutton.on_click(compute_selected_method)
        self.actionbox = HBox([
            self.namingbox,
            Separator('.'),
            self.searchbox,
            Separator('('),
            self.inputbox,
            self.inputbutton,
            Separator(')'),
            self.gobutton
        ])
        self.outputbox = ExplorerOutput(obj)
        self.helpbox = ExplorerHelp(obj)
        self.helpbox.update_title(self.description.content + " ..")

        self.bottom = VBox([self.actionbox, self.outputbox, self.helpbox])

        self.children = (self.top, self.bottom)
Example #55
0
class SequenceViewer(VBox):
    """
    SequenceViewer

    Arguments:
        title (str) - Title of sequence
        function (callable) - takes an index 0 to length - 1. Function should
            a displayable or list of displayables
        length (int) - total number of frames in sequence
        play_rate (float) - seconds to wait between frames when auto-playing.
            Optional. Default is 0.5 seconds.

    >>> def function(index):
    ...     return [None]
    >>> sv = SequenceViewer("Title", function, 10)
    >>> ## Do this manually for testing:
    >>> sv.initialize()
    None
    >>> ## Testing:
    >>> class Dummy:
    ...     def update(self, result):
    ...         return result
    >>> sv.displayers = [Dummy()]
    >>> print("Testing"); sv.goto("begin") # doctest: +ELLIPSIS
    Testing...
    >>> print("Testing"); sv.goto("end") # doctest: +ELLIPSIS
    Testing...
    >>> print("Testing"); sv.goto("prev") # doctest: +ELLIPSIS
    Testing...
    >>> print("Testing"); sv.goto("next") # doctest: +ELLIPSIS
    Testing...

    """
    def __init__(self, title, function, length, play_rate=0.5):
        self.player = _Player(self, play_rate)
        self.player.start()
        self.title = title
        self.function = function
        self.length = length
        self.output = Output()
        self.position_text = IntText(value=0, layout=Layout(width="100%"))
        self.total_text = Label(value="of %s" % self.length, layout=Layout(width="100px"))
        controls = self.make_controls()
        super().__init__([controls, self.output])

    def goto(self, position):
        #### Position it:
        if position == "begin":
            self.control_slider.value = 0
        elif position == "end":
            self.control_slider.value = self.length - 1
        elif position == "prev":
            if self.control_slider.value - 1 < 0:
                self.control_slider.value = self.length - 1 # wrap around
            else:
                self.control_slider.value = max(self.control_slider.value - 1, 0)
        elif position == "next":
            if self.control_slider.value + 1 > self.length - 1:
                self.control_slider.value = 0 # wrap around
            else:
                self.control_slider.value = min(self.control_slider.value + 1, self.length - 1)
        elif isinstance(position, int):
            self.control_slider.value = position
        self.position_text.value = self.control_slider.value

    def toggle_play(self, button):
        ## toggle
        if self.button_play.description == "Play":
            self.button_play.description = "Stop"
            self.button_play.icon = "pause"
            self.player.resume()
        else:
            self.button_play.description = "Play"
            self.button_play.icon = "play"
            self.player.pause()

    def make_controls(self):
        button_begin = Button(icon="fast-backward", layout=Layout(width='100%'))
        button_prev = Button(icon="backward", layout=Layout(width='100%'))
        button_next = Button(icon="forward", layout=Layout(width='100%'))
        button_end = Button(icon="fast-forward", layout=Layout(width='100%'))
        self.button_play = Button(icon="play", description="Play", layout=Layout(width="100%"))
        self.control_buttons = HBox([
            button_begin,
            button_prev,
            self.position_text,
            button_next,
            button_end,
            self.button_play,
        ], layout=Layout(width='100%', height="50px"))
        self.control_slider = IntSlider(description=self.title,
                                        continuous_update=False,
                                        min=0,
                                        max=max(self.length - 1, 0),
                                        value=0,
                                        style={"description_width": 'initial'},
                                        layout=Layout(width='100%'))
        ## Hook them up:
        button_begin.on_click(lambda button: self.goto("begin"))
        button_end.on_click(lambda button: self.goto("end"))
        button_next.on_click(lambda button: self.goto("next"))
        button_prev.on_click(lambda button: self.goto("prev"))
        self.button_play.on_click(self.toggle_play)
        self.control_slider.observe(self.update_slider_control, names='value')
        controls = VBox([HBox([self.control_slider, self.total_text], layout=Layout(height="40px")),
                         self.control_buttons], layout=Layout(width='100%'))
        controls.on_displayed(lambda widget: self.initialize())
        return controls

    def initialize(self):
        results = self.function(self.control_slider.value)
        try:
            results = list(results)
        except:
            results = [results]
        self.displayers = [display(x, display_id=True) for x in results]

    def update_slider_control(self, change):
        if change["name"] == "value":
            self.position_text.value = self.control_slider.value
            self.output.clear_output(wait=True)
            results = self.function(self.control_slider.value)
            try:
                results = list(results)
            except:
                results = [results]
            for i in range(len(self.displayers)):
                self.displayers[i].update(results[i])
Example #56
0
    def _init_gui(self, **kwargs):
        """Initialize generic GUI controls and observe callbacks."""
        mainopts = super(TensorContainer, self)._init_gui(**kwargs)
        scn = self.scenes[0]
        alo = Layout(width='74px')
        rlo = Layout(width='235px')
        if self._df is not None:
            scn.txx = self._df.loc[0,'xx']
            scn.txy = self._df.loc[0,'xy']
            scn.txz = self._df.loc[0,'xz']
            scn.tyx = self._df.loc[0,'yx']
            scn.tyy = self._df.loc[0,'yy']
            scn.tyz = self._df.loc[0,'yz']
            scn.tzx = self._df.loc[0,'zx']
            scn.tzy = self._df.loc[0,'zy']
            scn.tzz = self._df.loc[0,'zz']
        xs = [FloatText(value=scn.txx , layout=alo),
              FloatText(value=scn.txy , layout=alo),
              FloatText(value=scn.txz , layout=alo)]
        ys = [FloatText(value=scn.tyx , layout=alo),
              FloatText(value=scn.tyy , layout=alo),
              FloatText(value=scn.tyz , layout=alo)]
        zs = [FloatText(value=scn.tzx , layout=alo),
              FloatText(value=scn.tzy , layout=alo),
              FloatText(value=scn.tzz , layout=alo)]
        #scale =  FloatSlider(max=10.0, step=0.01, readout=True, value=1.0)
        opt = [0] if self._df is None else [int(x) for x in self._df.index.values]
        tensorIndex = Dropdown(options=opt, value=opt[0], layout=rlo)
        tdxlabel = Label(value='Select the tensor index:')
        def _x0(c):
            for scn in self.active(): scn.txx = c.new
        def _x1(c):
            for scn in self.active(): scn.txy = c.new
        def _x2(c):
            for scn in self.active(): scn.txz = c.new
        def _y0(c):
            for scn in self.active(): scn.tyx = c.new
        def _y1(c):
            for scn in self.active(): scn.tyy = c.new
        def _y2(c):
            for scn in self.active(): scn.tyz = c.new
        def _z0(c):
            for scn in self.active(): scn.tzx = c.new
        def _z1(c):
            for scn in self.active(): scn.tzy = c.new
        def _z2(c):
            for scn in self.active(): scn.tzz = c.new
        xs[0].observe(_x0, names='value')
        xs[1].observe(_x1, names='value')
        xs[2].observe(_x2, names='value')
        ys[0].observe(_y0, names='value')
        ys[1].observe(_y1, names='value')
        ys[2].observe(_y2, names='value')
        zs[0].observe(_z0, names='value')
        zs[1].observe(_z1, names='value')
        zs[2].observe(_z2, names='value')
        rlo = Layout(width='234px')
        xbox = HBox(xs, layout=rlo)
        ybox = HBox(ys, layout=rlo)
        zbox = HBox(zs, layout=rlo)
        geom = Button(icon='cubes', description=' Geometry', layout=_wlo)

        def _change_tensor(tdx=0):
            carts = ['x','y','z']
            for i, bra in enumerate(carts):
                for j, ket in enumerate(carts):
                    if i == 0:
                        xs[j].value = self._df.loc[tdx,bra+ket]
                    elif i == 1:
                        ys[j].value = self._df.loc[tdx,bra+ket]
                    elif i == 2:
                        zs[j].value = self._df.loc[tdx,bra+ket]

        def _geom(b):
            for scn in self.active(): scn.geom = not scn.geom

        def _tdx(c):
            for scn in self.active(): scn.tdx = c.new
            _change_tensor(c.new)

        geom.on_click(_geom)
        tensorIndex.observe(_tdx, names="value")
        mainopts.update([('geom', geom),
                         ('tlbl', tdxlabel),
                         ('tidx', tensorIndex),
                         ('xbox', xbox),
                         ('ybox', ybox),
                         ('zbox', zbox)])
        return mainopts
Example #57
0
def calendar(path):
    def show_imgs():
        print(f"Crop name: {crop_name},  Area: {area:.2f} sqm")

        def multi_bands_imgs(bands, fname):
            df = view_images.create_df(ci_path, pid, ci_band.value)
            rows = round((df.shape[0] / columns) + 0.5)
            fig = plt.figure(figsize=(16, 4 * rows))
            for i, row in df.iterrows():
                fig.add_subplot(rows, columns, i + 1)

                str_date = str(row['date'].date()).replace('-', '')
                img_png = f"{ci_path}{fname}_{str_date}.png"

                # Create color image if it does not exist
                # Merge bands (images path, export image path, bands list)
                if not os.path.isfile(img_png):
                    imgs_path = f"{ci_path}{row['imgs']}"
                    view_images.merge_bands(imgs_path, img_png, bands)

                with rasterio.open(img_png, format='PNG') as img:
                    """extracts the EPSG spatial reference"""
                    overlay_date(img, row['date'].date())  # Add date overlay.
                    ax = plt.gca()
                    if show_parcel.value:
                        ax.add_patch(overlay_parcel(img, info_data))

                    plt.axis('off')  # Turn of axis.
                    pA, pB = np.percentile(img.read(1),
                                           tuple(ci_percent.value))

                    # Strech image to A - B percentile.
                    stack = [
                        exposure.rescale_intensity(img.read()[i, :, :],
                                                   in_range=(pA, pB))
                        for i in range(len(bands))
                    ]
                    rgb_enhanced = np.dstack(stack)

                    show(np.uint16(rgb_enhanced.transpose(2, 0, 1) / 300),
                         ax=ax,
                         transform=img.transform)
            return plt.show()

        def ndvi_imgs(bands, fname):
            df = view_images.create_df(ci_path, pid, ci_band.value)
            rows = round((df.shape[0] / columns) + 0.5)
            fig = plt.figure(figsize=(16, 4 * rows))
            for i, row in df.iterrows():
                fig.add_subplot(rows, columns, i + 1)

                str_date = str(row['date'].date()).replace('-', '')
                img_png = f"{ci_path}{fname}_{str_date}.png"

                imgs_path = f"{ci_path}{row['imgs']}"
                b4f = f"{imgs_path}.B04.tif"
                b4 = rasterio.open(b4f, format='GTiff')

                ndvi = view_images.calc_ndvi(imgs_path, img_png, bands)
                overlay_date(b4, row['date'].date())  # Add date overlay.
                ax = plt.gca()
                if show_parcel.value:
                    ax.add_patch(overlay_parcel(b4, info_data))

                plt.axis('off')  # Turn of axis.
                pA, pB = np.percentile(ndvi, tuple(ci_percent.value))

                show(ndvi,
                     ax=ax,
                     transform=b4.transform,
                     cmap=ci_cmaps.value,
                     vmin=pA,
                     vmax=pB)

                b4.close()
            return plt.show()

        def single_band(band):
            df = view_images.create_df(ci_path, pid, ci_band.value)
            rows = round((df.shape[0] / columns) + 0.5)
            fig = plt.figure(figsize=(16, 4 * rows))
            for i, row in df.iterrows():
                img_gtif = f"{ci_path}{row['imgs']}.{ci_band.value[0]}.tif"
                with rasterio.open(img_gtif, format='GTiff') as img:
                    fig.add_subplot(rows, columns, i + 1)
                    overlay_date(img, row['date'].date())
                    plt.axis('off')
                    ax = plt.gca()
                    if show_parcel.value:
                        ax.add_patch(overlay_parcel(img, info_data))

                    img_read = img.read(1)

                    pA, pB = np.percentile(img_read, tuple(ci_percent.value))
                    show(img.read(1),
                         ax=ax,
                         transform=img.transform,
                         cmap=data_options.cmaps(ci_band.value[0]),
                         vmin=pA,
                         vmax=pB)

            return plt.show()

        if len(ci_band.value) == 1:
            single_band(ci_band.value[0])
        elif ci_band.value == ['B04', 'B08']:
            ndvi_imgs(ci_band.value, 'NDVI')
        else:
            multi_bands_imgs(ci_band.value, ('').join(ci_band.value))

    def overlay_date(img, date):
        date_text = plt.text(
            img.bounds.left + ((img.bounds.right - img.bounds.left) / 6.5),
            img.bounds.top - ((img.bounds.top - img.bounds.bottom) / 6.5),
            date,
            color='yellow',
            weight='bold',
            size=12,
            bbox=dict(boxstyle="round", ec='yellow', fc='black', alpha=0.2))
        return date_text

    def overlay_parcel(img, info_data):
        img_epsg = img.crs.to_epsg()
        geo_json = view_spatial.trasform_geometry(info_data, img_epsg)
        patche = [
            PolygonPatch(feature,
                         edgecolor="yellow",
                         facecolor="none",
                         linewidth=2) for feature in [geo_json]
        ]
        return patche[0]

    # Images options.
    file_info = glob.glob(f"{path}*_information.json")[0]
    with open(file_info, 'r') as f:
        info_data = json.loads(f.read())
    pid = info_data['ogc_fid'][0]
    crop_name = info_data['cropname'][0]
    area = info_data['area'][0]
    ci_path = f"{path}{pid}_chip_images/"
    columns = 4

    available_options = view_images.available_options(path, pid)
    ci_band = Dropdown(
        options=available_options,
        description='Select band:',
        disabled=False,
    )

    ci_cmaps = Dropdown(options=data_options.color_maps(),
                        value='RdYlGn_r',
                        description='Color map:',
                        disabled=False,
                        layout=Layout(width='15%'))

    ci_percent = IntRangeSlider(
        value=[2, 98],
        min=0,
        max=100,
        step=1,
        description='%:',
        disabled=False,
        continuous_update=False,
        orientation='horizontal',
        readout=True,
        readout_format='d',
    )

    show_parcel = Checkbox(value=True,
                           description='Show parcel',
                           disabled=False,
                           indent=False,
                           layout=Layout(width='100px'))

    ci_cloud = Checkbox(value=False,
                        description='Cloud free',
                        disabled=True,
                        indent=False,
                        layout=Layout(width='140px'))

    btn_ci = Button(value=False,
                    description='Show images',
                    disabled=False,
                    button_style='info',
                    tooltip='Refresh output',
                    icon='')

    ci_out = Output()

    @btn_ci.on_click
    def btn_ci_on_click(b):
        btn_ci.description = 'Refresh'
        btn_ci.icon = 'refresh'
        with ci_out:
            ci_out.clear_output()
            show_imgs()

    wbox_ci_cloud = HBox([])
    if len([val for key, val in available_options if 'SCL' in val]) > 0:
        wbox_ci_cloud = HBox([ci_cloud])

    wbox_ci = HBox([btn_ci, ci_band, show_parcel, ci_percent, wbox_ci_cloud])

    def ci_band_change(change):
        if len(ci_band.value) == 1:
            if ci_band.value[0] in ['B02', 'B03', 'B04', 'B08']:
                wbox_ci.children = [btn_ci, ci_band, show_parcel, ci_percent]
                show_parcel.value = True
            else:
                wbox_ci.children = [btn_ci, ci_band, ci_percent]
                show_parcel.value = False
        elif ci_band.value == ['B04', 'B08']:
            wbox_ci.children = [
                btn_ci, ci_band, show_parcel, ci_cmaps, ci_percent,
                wbox_ci_cloud
            ]
            show_parcel.value = True
        else:
            wbox_ci.children = [
                btn_ci, ci_band, show_parcel, ci_percent, wbox_ci_cloud
            ]
            show_parcel.value = True

    ci_band.observe(ci_band_change, 'value')

    wbox = VBox([wbox_ci, ci_out])

    return wbox
Example #58
0
    def _tensor_folder(self):
        alo = Layout(width='70px')
        rlo = Layout(width='220px')
        scale =  FloatSlider(max=10.0, step=0.001, readout=True, value=1.0)
        xs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        ys = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        zs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        cs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        cidx = HBox([Text(disabled=True,description='Atom Index',layout=rlo)])
        xbox = HBox(xs, layout=rlo)
        ybox = HBox(ys, layout=rlo)
        zbox = HBox(zs, layout=rlo)
        cbox = HBox(cs, layout=rlo)
        tens = Button(description=' Tensor', icon='bank')
        tensor_cont = VBox([xbox,ybox,zbox])
        tensorIndex = Dropdown(options=[0],value=0,description='Tensor')
#        sceneIndex = Dropdown(options=[0],value=0,description='Scene')
        ten_label = Label(value="Change selected tensor:")
        sel_label = Label(value="Selected tensor in gray frame")
        cod_label = Label(value="Center of selected tensor: (x,y,z)")
        tensor = []
        self.coords = []

        def _changeTensor(tensor, tdx):
            carts = ['x','y','z']
            for i,bra in enumerate(carts):
                for j,ket in enumerate(carts):
                    tensor_cont.children[i].children[j].disabled=False
                    tensor_cont.children[i].children[j].value = \
                                            str(tensor[0][tdx][bra+ket])
                    tensor_cont.children[i].children[j].disabled=True
            adx = tensor[0][tdx]['atom']
            cidx.children[0].value = str(adx)
            cbox.children[0].value = str(self.coords[0][int(adx)])
            cbox.children[1].value = str(self.coords[1][int(adx)])
            cbox.children[2].value = str(self.coords[2][int(adx)])
#            scale.value = tensor[0][tdx]['scale']

        def _tens(c):
            for scn in self.active(): scn.tens = not scn.tens
            self.coords = self._filter_coords()
#            sceneIndex.options = [x for x in range(len(self.active()))]
#            sceneIndex.value = sceneIndex.options[0]
            tensor = self.active()[0].tensor_d
            tensorIndex.options = [x for x in range(len(tensor[0]))]
            tensorIndex.value = tensorIndex.options[0]
            tdx = tensorIndex.value
            _changeTensor(tensor, tdx)

        def _scale(c):
            for scn in self.active(): scn.scale = c.new
#            tdx = tensorIndex.value
#            tensor = self.active()[0].tensor_d
#            tensor[0][tdx]['scale'] = c.new

        def _idx(c):
            for scn in self.active(): scn.tidx = c.new
            tensor = self.active()[0].tensor_d
            tdx = c.new
            _changeTensor(tensor, tdx)

#        def _sdx(c):
#            tensor = self.active()[sceneIndex.value].tensor_d
#            tensorIndex.options = [x for x in range(len(tensor[0]))]
#            tensorIndex.value = tensorIndex.options[0]
#            tdx = tensorIndex.value
#            _changeTensor(tensor, tdx)

        tens.on_click(_tens)
        scale.observe(_scale, names='value')
        tensorIndex.observe(_idx, names='value')
#        sceneIndex.observe(_sdx, names='value')
        content = _ListDict([
                ('scale', scale),
                ('ten', ten_label),
#               ('sdx', sceneIndex),
                ('tdx', tensorIndex),
                ('tensor', tensor_cont),
                ('sel', sel_label),
                ('cidx', cidx),
                ('center', cod_label),
                ('coord', cbox)])
        return Folder(tens, content)
Example #59
-1
    def __init__(self,figsize=(6,6)):
        self.figsize=figsize
        self.size_slider=IntSlider(description='Grid Size',min=4,max=50)
        display(self.size_slider)

        self.nb_ob_slider=IntSlider(description='Obstacles',min=0,max=7)
        display(self.nb_ob_slider)

        self.gen_inst_button=Button(description='Generate Instance',margin=10)
        self.gen_pos_button=Button(description='Generate Start/End Positions',margin=10)
        self.gen_path_button=Button(description='Generate Path',margin=10)
        self.inst_but_container=HBox(children=[self.gen_inst_button,self.gen_pos_button,self.gen_path_button])
        self.inst_but_container.width = '100%'
        display(self.inst_but_container)

        self.show_path_button=Latex(value='Path: Value:  Actions:',margin=10)
        display(self.show_path_button)

        self.size_slider.on_trait_change(self._on_size_slider_change,'value')
        self.gen_inst_button.on_click(self._on_gen_inst_button_click)
        self.gen_pos_button.on_click(self._on_pos_button_click)
        self.gen_path_button.on_click(self._on_gen_path_button_click)
        
        self.gen_path_button.disabled=True            
        self.fig=plt.figure(figsize=self.figsize)
        self.ax=self.fig.add_subplot(111)        
        
        self.A=np.zeros((4,4),dtype='int')
        self.replot_grid()        
        
        self.cid=self.fig.canvas.mpl_connect('button_press_event',self.onclick)
        self.mod=False
Example #60
-1
    def __init__(self,figsize=(6,6)):
        self.figsize=figsize
        self.size_slider=IntSlider(description='Grid Size',min=4,max=50)
        display(self.size_slider)

        self.nb_ob_slider=IntSlider(description='Obstacles',min=0,max=7)
        display(self.nb_ob_slider)

        self.gen_inst_button=Button(description='Generate Instance',margin=10)
        self.gen_pos_button=Button(description='Generate Start/End Positions',margin=10)
        self.gen_path_button=Button(description='Generate Path',margin=10)
        self.inst_but_container=HBox(children=[self.gen_inst_button,self.gen_pos_button,self.gen_path_button])
        self.inst_but_container.width = '100%'
        display(self.inst_but_container)


        self.show_path_button=Latex(value='Path: Value:  Actions:',margin=10)
        display(self.show_path_button)

        self.size_slider.on_trait_change(self._on_size_slider_change,'value')
        self.gen_inst_button.on_click(self._on_gen_inst_button_click)
        self.gen_pos_button.on_click(self._on_pos_button_click)
        self.gen_path_button.on_click(self._on_gen_path_button_click)
        
        self.gen_path_button.disabled=True
        self.gen_pos_button.disabled=True
            
        plt.close()
        plt.axis('off')
        self.fig=plt.figure(figsize=self.figsize)
        self.ax=self.fig.add_subplot(111)