Exemple #1
0
 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
Exemple #2
0
    def __init__(self, atoms, xsize=500, ysize=500):
        import nglview
        from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox
        self.atoms = atoms
        if isinstance(atoms[0], Atoms):
            # Assume this is a trajectory or struct list
            self.view = nglview.show_asetraj(atoms)
            self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1)
            self.frm.observe(self._update_frame)
            self.struct = atoms[0]
        else:
            # Assume this is just a single structure
            self.view = nglview.show_ase(atoms)
            self.struct = atoms
            self.frm = None

        self.colors = {}
        self.view._remote_call('setSize', target='Widget',
                               args=['%dpx' % (xsize,), '%dpx' % (ysize,)])
        self.view.add_unitcell()
        self.view.add_spacefill()
        self.view.camera = 'orthographic'
        self.view.update_spacefill(radiusType='covalent', scale=0.7)
        self.view.center()

        self.asel = Dropdown(options=['All'] +
                             list(set(self.struct.get_chemical_symbols())),
                             value='All', description='Show')

        self.rad = FloatSlider(value=0.8, min=0.0, max=1.5, step=0.01,
                               description='Ball size')

        self.asel.observe(self._select_atom)
        self.rad.observe(self._update_repr)

        wdg = [self.asel, self.rad]
        if self.frm:
            wdg.append(self.frm)

        self.gui = HBox([self.view, VBox(wdg)])
        # Make useful shortcuts for the user of the class
        self.gui.view = self.view
        self.gui.control_box = self.gui.children[1]
        self.gui.custom_colors = self.custom_colors
Exemple #3
0
class TrajectoryPlayer(DOMWidget):
    # should set default values here different from desired defaults
    # so `observe` can be triggered
    step = Int(0).tag(sync=True)
    sync_frame = Bool(True).tag(sync=True)
    interpolate = Bool(False).tag(sync=False)
    delay = Float(0.0).tag(sync=True)
    parameters = Dict().tag(sync=True)
    iparams = Dict().tag(sync=False)
    _interpolation_t = Float().tag(sync=False)
    _iterpolation_type = CaselessStrEnum(['linear', 'spline']).tag(sync=False)
    spin = Bool(False).tag(sync=False)
    _spin_x = Int(1).tag(sync=False)
    _spin_y = Int(0).tag(sync=False)
    _spin_z = Int(0).tag(sync=False)
    _spin_speed = Float(0.005).tag(sync=False)
    camera = CaselessStrEnum(['perspective', 'orthographic'],
        default_value='perspective').tag(sync=False)
    _render_params = Dict().tag(sync=False)
    _real_time_update = Bool(False).tag(sync=False)

    widget_tab = Any(None).tag(sync=False)
    widget_repr = Any(None).tag(sync=False)
    widget_repr_parameters = Any(None).tag(sync=False)
    widget_quick_repr = Any(None).tag(sync=False)
    widget_general = Any(None).tag(sync=False)
    widget_picked = Any(None).tag(sync=False)
    widget_preference = Any(None).tag(sync=False)
    widget_extra = Any(None).tag(sync=False)
    widget_theme = Any(None).tag(sync=False)
    widget_help = Any(None).tag(sync=False)
    widget_export_image = Any(None).tag(sync=False)
    widget_component_slider = Any(None).tag(sync=False)
    widget_repr_slider = Any(None).tag(sync=False)
    widget_repr_choices = Any(None).tag(sync=False)
    widget_repr_control_buttons = Any(None).tag(sync=False)
    widget_repr_add = Any(None).tag(sync=False)
    widget_accordion_repr_parameters = Any(None).tag(sync=False)
    widget_repr_parameters_dialog = Any(None).tag(sync=False)
    widget_repr_name = Any(None).tag(sync=False)
    widget_component_dropdown = Any(None).tag(sync=False)
    widget_drag = Any(None).tag(sync=False)

    def __init__(self, view, step=1, delay=100,
                 sync_frame=False, min_delay=40):
        self._view = view
        self.step = step
        self.sync_frame = sync_frame
        self.delay = delay
        self.min_delay = min_delay
        self._interpolation_t = 0.5
        self._iterpolation_type = 'linear'
        self.iparams = dict(
            t=self._interpolation_t,
            step=1,
            type=self._iterpolation_type)
        self._render_params = dict(factor=4,
                                   antialias=True,
                                   trim=False,
                                   transparent=False)

        self._widget_names = [w for w in dir(self) if w.startswith('wiget_')]
        self.observe(self._on_widget_built, names=['widget_repr_parameters',
            'widget_repr',
            'widget_preference'])
        self._movie_maker = None

    def _on_widget_built(self, change):
        widget = change['new']
        if widget is not None:
            widget.layout.padding = '5%'

    def _update_padding(self, padding=default.DEFAULT_PADDING):
        widget_collection = [
                self.widget_general,
                self.widget_repr,
                self.widget_preference,
                self.widget_repr_parameters,
                self.widget_help,
                self.widget_extra,
                self.widget_picked
        ]
        for widget in widget_collection:
            if widget is not None:
                widget.layout.padding = padding

    def _create_all_widgets(self):
        if self.widget_tab is None:
            self.widget_tab = self._display()

        old_index = self.widget_tab.selected_index
        for index, _ in enumerate(self.widget_tab.children):
            self.widget_tab.selected_index = index

        self.widget_tab.selected_index = old_index

    def smooth(self):
        self.interpolate = True

    @observe('camera')
    def on_camera_changed(self, change):
        camera_type = change['new']
        self._view._remote_call("setParameters",
                                target='Stage',
                                kwargs=dict(cameraType=camera_type))

    @property
    def frame(self):
        return self._view.frame

    @frame.setter
    def frame(self, value):
        self._view.frame = value

    @property
    def count(self):
        return self._view.count

    @observe('sync_frame')
    def update_sync_frame(self, change):
        value = change['new']
        if value:
            self._view._set_sync_frame()
        else:
            self._view._set_unsync_frame()

    @observe("delay")
    def update_delay(self, change):
        delay = change['new']
        self._view._set_delay(delay)

    @observe('parameters')
    def update_parameters(self, change):
        params = change['new']
        self.sync_frame = params.get("sync_frame", self.sync_frame)
        self.delay = params.get("delay", self.delay)
        self.step = params.get("step", self.step)

    @observe('_interpolation_t')
    def _interpolation_t_changed(self, change):
        self.iparams['t'] = change['new']

    @observe('spin')
    def on_spin_changed(self, change):
        self.spin = change['new']
        if self.spin:
            self._view._set_spin([self._spin_x, self._spin_y, self._spin_z],
                                 self._spin_speed)
        else:
            # stop
            self._view._set_spin(None, None)

    @observe('_spin_x')
    def on_spin_x_changed(self, change):
        self._spin_x = change['new']
        if self.spin:
            self._view._set_spin([self._spin_x, self._spin_y, self._spin_z],
                                 self._spin_speed)

    @observe('_spin_y')
    def on_spin_y_changed(self, change):
        self._spin_y = change['new']
        if self.spin:
            self._view._set_spin([self._spin_x, self._spin_y, self._spin_z],
                                 self._spin_speed)

    @observe('_spin_z')
    def on_spin_z_changed(self, change):
        self._spin_z = change['new']
        if self.spin:
            self._view._set_spin([self._spin_x, self._spin_y, self._spin_z],
                                 self._spin_speed)

    @observe('_spin_speed')
    def on_spin_speed_changed(self, change):
        self._spin_speed = change['new']
        if self.spin:
            self._view._set_spin([self._spin_x, self._spin_y, self._spin_z],
                                 self._spin_speed)

    def _display(self):
        box_factory = [(self._make_general_box, 'General'),
                       (self._make_widget_repr, 'Representation'),
                       (self._make_widget_preference, 'Preference'),
                       (self._make_theme_box, 'Theme'),
                       (self._make_extra_box, 'Extra'),
                       (self._show_website, 'Help')]

        tab = _make_delay_tab(box_factory, selected_index=-1)
        # tab = _make_autofit(tab)
        tab.layout.align_self = 'center'
        tab.layout.align_items = 'stretch'

        self.widget_tab = tab

        return self.widget_tab

    def _make_widget_tab(self):
        return self._display()

    def _make_button_center(self):
        button = Button(description=' Center', icon='fa-bullseye')
        @button.on_click
        def on_click(button):
            self._view.center()
        return button

    def _make_button_theme(self):
        button = Button(description='Oceans16')
        @button.on_click
        def on_click(button):
            from nglview import theme
            display(theme.oceans16())
            self._view._remote_call('cleanOutput',
                                    target='Widget')
        return button

    def _make_button_reset_theme(self, hide_toolbar=False):
        from nglview import theme

        if hide_toolbar:
            button = Button(description='Simplified Default')
            @button.on_click
            def on_click(button):
                theme.reset(hide_toolbar=True)
        else:
            button = Button(description='Default')
            @button.on_click
            def on_click(button):
                theme.reset()
        return button

    def _make_button_clean_error_output(self):
        button = Button(description='Clear Error')
        @button.on_click
        def on_click(_):
            js_utils.clean_error_output()
        return button

    def _make_widget_preference(self, width='100%'):
        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.layout.width = default.DEFAULT_SLIDER_WIDTH
            return widget_sliders

        if self.widget_preference is None:
            widget_sliders = make_widget_box()
            reset_button = Button(description='Reset')
            widget_sliders.children = [reset_button,] + list(widget_sliders.children)

            @reset_button.on_click
            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)

            self.widget_preference = _relayout_master(widget_sliders, width=width)
        return self.widget_preference

    def _show_download_image(self):
        # "interactive" does not work for True/False in ipywidgets 4 yet.
        button = Button(description=' Screenshot', icon='fa-camera')
        @button.on_click
        def on_click(button):
            self._view.download_image()
        return button

    def _make_button_url(self, url, description):
        button = Button(description=description)

        @button.on_click
        def on_click(button):
            display(Javascript(js_utils.open_url_template.format(url=url)))
        return button

    def _show_website(self, ngl_base_url=default.NGL_BASE_URL):
        buttons = [self._make_button_url(url.format(ngl_base_url), description) for url, description in
            [("'http://arose.github.io/nglview/latest/'", "nglview"),
             ("'{}/index.html'", "NGL"),
             ("'{}/tutorial-selection-language.html'", "Selection"),
             ("'{}/tutorial-molecular-representations.html'", "Representation")]
        ]
        self.widget_help = _make_autofit(HBox(buttons))
        return self.widget_help

    def _make_button_qtconsole(self):
        from nglview import js_utils
        button = Button(description='qtconsole',
                tooltip='pop up qtconsole')

        @button.on_click
        def on_click(button):
            js_utils.launch_qtconsole()
        return button

    def _make_text_picked(self):
        ta = Textarea(value=json.dumps(self._view.picked), description='Picked atom')
        ta.layout.width = '300px'
        return ta

    def _refresh(self, component_slider, repr_slider):
        """update representation and component information
        """
        self._view._request_repr_parameters(component=component_slider.value,
                                            repr_index=repr_slider.value)
        self._view._remote_call('requestReprInfo', target='Widget')
        self._view._handle_repr_dict_changed(change=dict(new=self._view._repr_dict))

    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

    def _make_widget_repr(self):
        self.widget_repr_name = Text(value='', description='representation')
        self.widget_repr_name._ngl_name = 'repr_name_text'
        repr_selection = Text(value=' ', description='selection')
        repr_selection._ngl_name = 'repr_selection'
        repr_selection.width = self.widget_repr_name.width = default.DEFAULT_TEXT_WIDTH 

        max_n_components = max(self._view.n_components-1, 0)
        self.widget_component_slider = IntSlider(value=0, max=max_n_components, min=0, description='component')
        self.widget_component_slider._ngl_name = 'component_slider'

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

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

        self.widget_component_slider.layout.width = default.DEFAULT_SLIDER_WIDTH
        self.widget_repr_slider.layout.width = default.DEFAULT_SLIDER_WIDTH
        self.widget_component_dropdown.layout.width = self.widget_component_dropdown.max_width = default.DEFAULT_TEXT_WIDTH

        # turn off for now
        self.widget_component_dropdown.layout.display = 'none'
        self.widget_component_dropdown.description = ''

        # self.widget_accordion_repr_parameters = Accordion()
        self.widget_accordion_repr_parameters = Tab()
        self.widget_repr_parameters =  self._make_widget_repr_parameters(self.widget_component_slider,
                self.widget_repr_slider,
                self.widget_repr_name)
        self.widget_accordion_repr_parameters.children = [self.widget_repr_parameters, Box()]
        self.widget_accordion_repr_parameters.set_title(0, 'Parameters')
        self.widget_accordion_repr_parameters.set_title(1, 'Hide')
        self.widget_accordion_repr_parameters.selected_index = 1
        
        checkbox_reprlist = Checkbox(value=False, description='reprlist')
        checkbox_reprlist._ngl_name = 'checkbox_reprlist'
        self.widget_repr_choices = self._make_repr_name_choices(self.widget_component_slider,
                self.widget_repr_slider)
        self.widget_repr_choices._ngl_name = 'reprlist_choices'

        self.widget_repr_add = self._make_add_widget_repr(self.widget_component_slider)

        def on_update_checkbox_reprlist(change):
            self.widget_repr_choices.visible= change['new']
        checkbox_reprlist.observe(on_update_checkbox_reprlist, names='value')

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

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

            if should_update:
                component=self.widget_component_slider.value
                repr_index=self.widget_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 on_component_or_repr_slider_value_changed(change):
            self._view._request_repr_parameters(component=self.widget_component_slider.value,
                                                repr_index=self.widget_repr_slider.value)
            self.widget_component_dropdown.options = tuple(self._view._ngl_component_names)

            if self.widget_accordion_repr_parameters.selected_index >= 0:
                self.widget_repr_parameters.name = self.widget_repr_name.value
                self.widget_repr_parameters.repr_index = self.widget_repr_slider.value
                self.widget_repr_parameters.component_index = self.widget_component_slider.value

        def on_repr_selection_value_changed(change):
            if self._real_time_update:
                component = self.widget_component_slider.value
                repr_index = self.widget_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:
                 self.widget_component_slider.value = self._view._ngl_component_names.index(choice)

        self.widget_component_dropdown.observe(on_change_component_dropdown, names='value')

        self.widget_repr_slider.observe(on_component_or_repr_slider_value_changed, names='value')
        self.widget_component_slider.observe(on_component_or_repr_slider_value_changed, names='value')
        self.widget_repr_name.observe(on_repr_name_text_value_changed, names='value')
        repr_selection.observe(on_repr_selection_value_changed, names='value')

        self.widget_repr_control_buttons = self._make_button_repr_control(self.widget_component_slider,
        self.widget_repr_slider, repr_selection)

        blank_box = Box([Label("")])

        all_kids = [self.widget_repr_control_buttons,
                    blank_box,
                    self.widget_repr_add,
                    self.widget_component_dropdown,
                    self.widget_repr_name,
                    repr_selection,
                    self.widget_component_slider,
                    self.widget_repr_slider,
                    self.widget_repr_choices,
                    self.widget_accordion_repr_parameters
        ]

        vbox = VBox(all_kids)

        self._view._request_repr_parameters(component=self.widget_component_slider.value,
            repr_index=self.widget_repr_slider.value)

        self.widget_repr = _relayout_master(vbox, width='100%')

        self._refresh(self.widget_component_slider, self.widget_repr_slider)

        setattr(self.widget_repr, "_saved_widgets", [])
        for _box in self.widget_repr.children:
            if hasattr(_box, 'children'):
                for kid in _box.children:
                    self.widget_repr._saved_widgets.append(kid)

        return self.widget_repr

    def _make_widget_repr_parameters(self, component_slider, repr_slider, repr_name_text=None):
        name = repr_name_text.value if repr_name_text is not None else ' '
        widget = self._view._display_repr(component=component_slider.value,
                                          repr_index=repr_slider.value,
                                          name=name)
        widget._ngl_name = 'repr_parameters_box'
        return widget

    def _make_button_export_image(self):
        slider_factor = IntSlider(value=4, min=1, max=10, description='scale')
        checkbox_antialias = Checkbox(value=True, description='antialias')
        checkbox_trim = Checkbox(value=False, description='trim')
        checkbox_transparent = Checkbox(value=False, description='transparent')
        filename_text = Text(value='Screenshot', description='Filename')
        delay_text = FloatText(value=1, description='delay (s)', tooltip='hello')

        start_text, stop_text, step_text = (IntText(value=0, description='start'),
                                            IntText(value=self._view.count, description='stop'),
                                            IntText(value=1, description='step'))

        start_text.layout.max_width = stop_text.layout.max_width = step_text.layout.max_width \
                = filename_text.layout.max_width = delay_text.layout.max_width = default.DEFAULT_TEXT_WIDTH

        button_movie_images = Button(description='Export Images')
        def download_image(filename):
            self._view.download_image(factor=slider_factor.value,
                    antialias=checkbox_antialias.value,
                    trim=checkbox_trim.value,
                    transparent=checkbox_transparent.value,
                    filename=filename)

        @button_movie_images.on_click
        def on_click_images(button_movie_images):
            for i in range(start_text.value, stop_text.value, step_text.value):
                self._view.frame = i
                time.sleep(delay_text.value)
                download_image(filename=filename_text.value + str(i))
                time.sleep(delay_text.value)

        vbox = VBox([
            button_movie_images,
            start_text,
            stop_text,
            step_text,
            delay_text,
            filename_text,
            slider_factor,
            checkbox_antialias,
            checkbox_trim,
            checkbox_transparent,
            ])

        form_items = _relayout(vbox, make_form_item_layout())
        form = Box(form_items, layout=_make_box_layout())
        # form = _relayout_master(vbox)
        return form

    def _make_resize_notebook_slider(self):
        resize_notebook_slider = IntSlider(min=300, max=2000, description='resize notebook')
        def on_resize_notebook(change):
            width = change['new']
            self._view._remote_call('resizeNotebook',
                    target='Widget',
                    args=[width,])
        resize_notebook_slider.observe(on_resize_notebook, names='value')
        return resize_notebook_slider

    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

    def _make_repr_playground(self):
        vbox = VBox()
        children = []

        rep_names = REPRESENTATION_NAMES[:]
        excluded_names = ['ball+stick', 'distance']
        for name in excluded_names:
            rep_names.remove(name)

        repr_selection = Text(value='*')
        repr_selection.layout.width = default.DEFAULT_TEXT_WIDTH
        repr_selection_box  = HBox([Label('selection'), repr_selection])
        setattr(repr_selection_box, 'value', repr_selection.value)

        for index, name in enumerate(rep_names):
            button = ToggleButton(description=name)

            def make_func():
                def on_toggle_button_value_change(change, button=button):
                    selection = repr_selection.value
                    new = change['new'] # True/False
                    if new:
                        self._view.add_representation(button.description, selection=selection)
                    else:
                        self._view._remove_representations_by_name(button.description)
                return on_toggle_button_value_change

            button.observe(make_func(), names='value')
            children.append(button)

        button_clear = Button(description='clear', button_style='info',
                icon='fa-eraser')

        @button_clear.on_click
        def on_clear(button_clear):
            self._view.clear()
            for kid in children:
                # unselect
                kid.value = False

        vbox.children = children + [repr_selection, button_clear]
        _make_autofit(vbox)
        self.widget_quick_repr = vbox
        return self.widget_quick_repr

    def _make_repr_name_choices(self, component_slider, repr_slider):
        repr_choices = Dropdown(options=[" ",])

        def on_chose(change):
            repr_name = change['new']
            repr_index = repr_choices.options.index(repr_name)
            repr_slider.value = repr_index

        repr_choices.observe(on_chose, names='value')
        repr_choices.layout.width = default.DEFAULT_TEXT_WIDTH

        self.widget_repr_choices = repr_choices
        return self.widget_repr_choices

    def _make_drag_widget(self):
        button_drag = Button(description='widget drag: off', tooltip='dangerous')
        drag_nb = Button(description='notebook drag: off', tooltip='dangerous')
        button_reset_notebook = Button(description='notebook: reset', tooltip='reset?')
        button_dialog = Button(description='dialog', tooltip='make a dialog')
        button_split_half = Button(description='split screen', tooltip='try best to make a good layout')

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

        @drag_nb.on_click
        def on_drag_nb(button_drag):
            if drag_nb.description == 'notebook drag: off':
                js_utils._set_notebook_draggable(True)
                drag_nb.description = 'notebook drag: on'
            else:
                js_utils._set_notebook_draggable(False)
                drag_nb.description = 'notebook drag: off'

        @button_reset_notebook.on_click
        def on_reset(button_reset_notebook):
            js_utils._reset_notebook()

        @button_dialog.on_click
        def on_dialog(button_dialog):
            self._view._remote_call('setDialog', target='Widget')

        @button_split_half.on_click
        def on_split_half(button_dialog):
            from nglview import js_utils
            import time
            js_utils._move_notebook_to_the_left()
            js_utils._set_notebook_width('5%')
            time.sleep(0.1)
            self._view._remote_call('setDialog', target='Widget')

        drag_box = HBox([button_drag, drag_nb, button_reset_notebook,
                        button_dialog, button_split_half])
        drag_box = _make_autofit(drag_box)
        self.widget_drag = drag_box
        return drag_box

    def _make_spin_box(self):
        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')
        # 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'))

        spin_box= VBox([checkbox_spin,
                   spin_x_slide,
                   spin_y_slide,
                   spin_z_slide,
                   spin_speed_slide])
        spin_box = _relayout_master(spin_box, width='75%')
        return spin_box

    def _make_widget_picked(self):
        self.widget_picked = self._make_text_picked()
        picked_box = HBox([self.widget_picked,])
        return _relayout_master(picked_box, width='75%')

    def _make_export_image_widget(self):
        if self.widget_export_image is None:
            self.widget_export_image = HBox([self._make_button_export_image()])
        return self.widget_export_image

    def _make_extra_box(self):
        if self.widget_extra is None:
            extra_list = [(self._make_drag_widget, 'Drag'),
                          (self._make_spin_box, 'Spin'),
                          (self._make_widget_picked, 'Picked'),
                          (self._make_repr_playground, 'Quick'),
                          (self._make_export_image_widget, 'Image'),
                          (self._make_command_box, 'Command')]

            extra_box = _make_delay_tab(extra_list, selected_index=0)
            self.widget_extra = extra_box
        return self.widget_extra

    def _make_theme_box(self):
        if self.widget_theme is None:
            self.widget_theme = Box([self._make_button_theme(),
                                     self._make_button_reset_theme(hide_toolbar=False),
                                     self._make_button_reset_theme(hide_toolbar=True),
                                     self._make_button_clean_error_output()])
        return self.widget_theme

    def _make_general_box(self):
        if self.widget_general is None:
            step_slide = IntSlider(
                value=self.step,
                min=-100,
                max=100,
                description='step')
            delay_text = IntSlider(
                value=self.delay,
                min=10,
                max=1000,
                description='delay')
            toggle_button_interpolate = ToggleButton(self.interpolate, description='Smoothing',
                                                     tooltip='smoothing trajectory')
            link((toggle_button_interpolate, 'value'), (self, 'interpolate'))

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

            link((step_slide, 'value'), (self, 'step'))
            link((delay_text, 'value'), (self, 'delay'))
            link((toggle_button_interpolate, 'value'), (self, 'interpolate'))
            link((camera_type, 'value'), (self, 'camera'))
            link((background_color_picker, 'value'), (self._view, 'background'))

            center_button = self._make_button_center()
            render_button = self._show_download_image()
            qtconsole_button = self._make_button_qtconsole()
            center_render_hbox = _make_autofit(HBox([toggle_button_interpolate, center_button,
                                                     render_button, qtconsole_button]))

            v0_left = VBox([step_slide,
                       delay_text,
                       background_color_picker,
                       camera_type,
                       center_render_hbox,
                       ])

            v0_left = _relayout_master(v0_left, width='100%')
            self.widget_general = v0_left
        return self.widget_general

    def _make_command_box(self):
        widget_text_command = Text()

        @widget_text_command.on_submit
        def _on_submit_command(_):
            command = widget_text_command.value
            js_utils.execute(command)
            widget_text_command.value = ''
        return widget_text_command

    def _create_all_tabs(self):
        tab = self._display()
        for index, _ in enumerate(tab.children):
            # trigger ceating widgets
            tab.selected_index = index

        self.widget_extra = self._make_extra_box()
        for index, _ in enumerate(self.widget_extra.children):
            self.widget_extra.selected_index = index

    def _simplify_repr_control(self):
        for widget in self.widget_repr._saved_widgets:
            if not isinstance(widget, Tab):
                widget.layout.display = 'none'
        self.widget_repr_choices.layout.display = 'flex'
        self.widget_accordion_repr_parameters.selected_index = 0
                  pulse_color='#9500ff')

# In[18]:

map.add_layer(my_path)
start_marker = Marker(location=(56.847962835674466, 35.9070110321045))
map.add_layer(start_marker)
finish_marker = Marker(location=(56.881189988867625, 35.927454334450935))
map.add_layer(finish_marker)
start = HTML()
finish = HTML()
start.value = 'Start'
finish.value = 'End'
start_marker.popup = start
finish_marker.popup = finish
zoom_slider = IntSlider(description='Zoom', min=11, max=15, value=14)
jslink((zoom_slider, 'value'), (m, 'zoom'))

# In[19]:

widget_control = WidgetControl(widget=zoom_slider, position='topright')
map.add_control(widget_control)
display(map)

# In[20]:

print(str(map))

# In[21]:

from sklearn.cluster import OPTICS
Exemple #5
0
def MidpointPseudoSectionWidget():
    ntx = xr.size - 2
    return widgetify(DipoleDipolefun,
                     i=IntSlider(min=0, max=ntx - 1, step=1, value=0))
Exemple #6
0
def DCIP2DfwdWidget():
    return widgetify(
        DC2DfwdWrapper,
        xc=FloatSlider(min=-1005.0,
                       max=1000.0,
                       step=10.0,
                       value=0.0,
                       continuous_update=False),
        zc=FloatSlider(min=-1000.0,
                       max=1000.0,
                       step=10.0,
                       value=250.0,
                       continuous_update=False),
        ellips_a=FloatSlider(min=10.0,
                             max=10000.0,
                             step=100.0,
                             value=1000.0,
                             continuous_update=False),
        ellips_b=FloatSlider(min=10.0,
                             max=10000.0,
                             step=100.0,
                             value=500.0,
                             continuous_update=False),
        rhohalf=FloatText(
            min=1e-8,
            max=1e8,
            value=1000.0,
            description="$\\rho_1$",
            continuous_update=False,
        ),
        chghalf=FloatText(
            min=0.0,
            max=100,
            value=0.0,
            description="$\\eta_1$",
            continuous_update=False,
        ),
        rholayer=FloatText(
            min=1e-8,
            max=1e8,
            value=100.0,
            description="$\\rho_2$",
            continuous_update=False,
        ),
        chglayer=FloatText(
            min=0.0,
            max=100,
            value=20.0,
            description="$\\eta_2$",
            continuous_update=False,
        ),
        rhoTarget=FloatText(
            min=1e-8,
            max=1e8,
            value=500.0,
            description="$\\rho_3$",
            continuous_update=False,
        ),
        chgTarget=FloatText(
            min=0.0,
            max=100,
            value=10.0,
            description="$\\eta_3$",
            continuous_update=False,
        ),
        overburden_thick=FloatSlider(min=0.0,
                                     max=1000.0,
                                     step=10.0,
                                     value=250.0,
                                     continuous_update=False),
        overburden_wide=fixed(2000.0),
        target_thick=FloatSlider(min=0.0,
                                 max=1000.0,
                                 step=10.0,
                                 value=200.0,
                                 continuous_update=False),
        target_wide=FloatSlider(min=0.0,
                                max=1000.0,
                                step=10.0,
                                value=200.0,
                                continuous_update=False),
        predmis=ToggleButtons(options=[
            "Data Without Target", "Difference", "Normalized Difference"
        ]),
        surveyType=ToggleButtons(
            options=["DipoleDipole", "PoleDipole", "DipolePole"],
            desciption="Array Type",
        ),
        which=ToggleButtons(options=["DC", "IP"], description="Survey"),
        nmax=IntSlider(min=1, max=16, value=8, description="Rx per Tx"),
        Scale=ToggleButtons(options=["Linear", "Log"]),
    )
Exemple #7
0
    def init_widgets(self):
        # Debug checkbox - enable logging in the Output widget
        self.debug = ipywidgets.Checkbox(description="Debug")
        self.debug.observe(self.controller.set_debug, names="value")

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

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

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

        # Size of environment when regenerating

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

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

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

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

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

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

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

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

        self.wMain = HBox([self.wImage, self.wVbox_controls])
Exemple #8
0
class View(object):
    """ The Jupyter Editor View - creates and holds the widgets comprising the Editor.
    """
    def __init__(self, editor, sGL="MPL"):
        self.editor = self.model = editor
        self.sGL = sGL

    def display(self):
        self.output_generator.clear_output()
        return self.wMain

    def init_canvas(self):
        # update the rendertool with the env
        self.new_env()
        self.oRT.render_env(show=False)
        img = self.oRT.get_image()
        self.wImage = jpy_canvas.Canvas(img)
        self.yxSize = self.wImage.data.shape[:2]
        self.writableData = np.copy(
            self.wImage.data
        )  # writable copy of image - wid_img.data is somehow readonly
        self.wImage.register_move(self.controller.on_mouse_move)
        self.wImage.register_click(self.controller.on_click)

        self.yxBase = self.oRT.gl.yxBase
        self.nPixCell = self.oRT.gl.nPixCell

    def init_widgets(self):
        # Debug checkbox - enable logging in the Output widget
        self.debug = ipywidgets.Checkbox(description="Debug")
        self.debug.observe(self.controller.set_debug, names="value")

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

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

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

        # Size of environment when regenerating

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

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

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

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

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

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

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

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

        self.wMain = HBox([self.wImage, self.wVbox_controls])

    def draw_stroke(self):
        pass

    def new_env(self):
        """ Tell the view to update its graphics when a new env is created.
        """
        self.oRT = rt.RenderTool(self.editor.env, gl=self.sGL)

    def redraw(self):
        with self.output_generator:
            self.oRT.set_new_rail()
            self.model.env.reset_agents()
            for a in self.model.env.agents:
                if hasattr(a, 'old_position') is False:
                    a.old_position = a.position
                if hasattr(a, 'old_direction') is False:
                    a.old_direction = a.direction

            self.oRT.render_env(agents=True,
                                show=False,
                                selected_agent=self.model.selected_agent,
                                show_observations=False)
            img = self.oRT.get_image()

            self.wImage.data = img
            self.writableData = np.copy(self.wImage.data)

            # the size should only be updated on regenerate at most
            self.yxSize = self.wImage.data.shape[:2]
            return img

    def redisplay_image(self):
        if self.writableData is not None:
            # This updates the image in the browser to be the new edited version
            self.wImage.data = self.writableData

    def drag_path_element(self, x, y):
        # Draw a black square on the in-memory copy of the image
        if x > 10 and x < self.yxSize[1] and y > 10 and y < self.yxSize[0]:
            self.writableData[(y - 2):(y + 2), (x - 2):(x + 2), :3] = 0

    def xy_to_rc(self, x, y):
        rc_cell = ((array([y, x]) - self.yxBase))
        nX = np.floor(
            (self.yxSize[0] - self.yxBase[0]) / self.model.env.height)
        nY = np.floor((self.yxSize[1] - self.yxBase[1]) / self.model.env.width)
        rc_cell[0] = max(
            0, min(np.floor(rc_cell[0] / nY), self.model.env.height - 1))
        rc_cell[1] = max(
            0, min(np.floor(rc_cell[1] / nX), self.model.env.width - 1))
        return rc_cell

    def log(self, *args, **kwargs):
        if self.output_generator:
            with self.output_generator:
                print(*args, **kwargs)
        else:
            print(*args, **kwargs)
Exemple #9
0
class SequenceViewer(VBox):
    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)
        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])
Exemple #10
0
# ### Interactive visualization across layers
# As another way of looking at the data, run the code below to create a visualization where you can choose the class you want to look at by clicking a button to choose a particular label and scrolling across layers using the slider!

# In[29]:


# Create button values
select_class = ToggleButtons(
    options=['Normal','Edema', 'Non-enhancing tumor', 'Enhancing tumor'],
    description='Select Class:',
    disabled=False,
    button_style='info', 
    
)
# Create layer slider
select_layer = IntSlider(min=0, max=154, description='Select Layer', continuous_update=False)

    
# Define a function for plotting images
def plot_image(seg_class, layer):
    print(f"Plotting {layer} Layer Label: {seg_class}")
    img_label = classes_dict[seg_class]
    mask = np.where(label_array[:,:,layer] == img_label, 255, 0)
    plt.figure(figsize=(10,5))
    plt.imshow(mask, cmap='gray')
    plt.axis('off');

# Use the interactive() tool to create the visualization
interactive(plot_image, seg_class=select_class, layer=select_layer)

Exemple #11
0
    def __init__(self,
                 filename,
                 cmap='jet',
                 band_indices=None,
                 pmin=2,
                 pmax=98,
                 ts_convert=None,
                 title=None,
                 datalabel='data'):

        self.ts_convert = ts_convert

        self.filename = filename
        with Raster(filename) as ras:
            self.rows = ras.rows
            self.cols = ras.cols
            self.bands = ras.bands
            self.epsg = ras.epsg
            self.crs = ras.srs
            geo = ras.raster.GetGeoTransform()
            self.nodata = ras.nodata
            self.format = ras.format
            if self.format == 'ENVI':
                self.bandnames = HDRobject(filename + '.hdr').band_names
                self.slider_readout = False

        self.timestamps = range(0, self.bands) if ts_convert is None else [
            ts_convert(x) for x in self.bandnames
        ]

        self.datalabel = datalabel

        xlab = self.crs.GetAxisName(None, 0)
        ylab = self.crs.GetAxisName(None, 1)
        self.xlab = xlab.lower() if xlab is not None else 'longitude'
        self.ylab = ylab.lower() if ylab is not None else 'latitude'

        self.xmin = geo[0]
        self.ymax = geo[3]
        self.xres = geo[1]
        self.yres = abs(geo[5])

        self.xmax = self.xmin + self.xres * self.cols
        self.ymin = self.ymax - self.yres * self.rows

        self.extent = (self.xmin, self.xmax, self.ymin, self.ymax)

        self.pmin, self.pmax = pmin, pmax

        # define some options for display of the widget box
        self.layout = Layout(display='flex',
                             flex_flow='column',
                             border='solid 2px',
                             align_items='stretch',
                             width='100%')

        self.colormap = cmap

        if band_indices is not None:
            if len(list(set(band_indices))) != self.bands:
                raise RuntimeError(
                    'length mismatch of unique provided band indices ({0}) '
                    'and image bands ({1})'.format(len(band_indices),
                                                   self.bands))
            else:
                self.indices = sorted(band_indices)
        else:
            self.indices = range(1, self.bands + 1)

        # define a slider for changing a plotted image
        self.slider = IntSlider(min=min(self.indices),
                                max=max(self.indices),
                                step=1,
                                continuous_update=False,
                                value=self.indices[len(self.indices) // 2],
                                description='band',
                                style={'description_width': 'initial'},
                                readout=self.slider_readout)

        # a simple checkbox to enable/disable stacking of vertical profiles into one plot
        self.checkbox = Checkbox(value=True,
                                 description='stack vertical profiles',
                                 indent=False)

        # a button to clear the vertical profile plot
        self.clearbutton = Button(description='clear vertical plot')
        self.clearbutton.on_click(lambda x: self.__init_vertical_plot())

        self.write_csv = Button(description='export csv')
        self.write_csv.on_click(lambda x: self.__csv())

        if self.format == 'ENVI':
            self.sliderlabel = Label(value=self.bandnames[self.slider.value],
                                     layout={'width': '500px'})
            children = [
                HBox([self.slider, self.sliderlabel]),
                HBox([self.checkbox, self.clearbutton, self.write_csv])
            ]
        else:
            children = [
                self.slider,
                HBox([self.checkbox, self.clearbutton, self.write_csv])
            ]

        form = VBox(children=children, layout=self.layout)

        display(form)

        self.fig = plt.figure(num=title)

        # display of SLC amplitude
        self.ax1 = self.fig.add_subplot(121)
        # display of topographical phase
        self.ax2 = self.fig.add_subplot(122)

        # self.ax1 = plt.gca()
        self.ax1.get_xaxis().get_major_formatter().set_useOffset(False)
        self.ax1.get_yaxis().get_major_formatter().set_useOffset(False)

        self.ax1.set_xlabel(self.xlab, fontsize=12)
        self.ax1.set_ylabel(self.ylab, fontsize=12)

        text_pointer = self.ylab + '={0:.2f}, ' + self.xlab + '={1:.2f}, value='
        self.ax1.format_coord = lambda x, y: text_pointer.format(y, x)

        # add a cross-hair to the horizontal slice plot
        self.x_coord, self.y_coord = self.__img2map(0, 0)
        self.lhor = self.ax1.axhline(self.y_coord, linewidth=1, color='r')
        self.lver = self.ax1.axvline(self.x_coord, linewidth=1, color='r')

        # set up the vertical profile plot
        self.__init_vertical_plot()

        # make the figure respond to mouse clicks by executing method __onclick
        self.cid1 = self.fig.canvas.mpl_connect('button_press_event',
                                                self.__onclick)

        # enable interaction with the slider
        out = interactive_output(self.__onslide, {'h': self.slider})

        plt.tight_layout()
Exemple #12
0
    def _make_widget_repr(self):
        # TODO: class?
        if self.widget_repr is None:
            self.widget_repr_name = Text(value='',
                                         description='representation')
            self.widget_repr_name._ngl_name = 'repr_name_text'
            repr_selection = Text(value=' ', description='selection')
            repr_selection._ngl_name = 'repr_selection'
            repr_selection.width = self.widget_repr_name.width = default.DEFAULT_TEXT_WIDTH

            max_n_components = max(self._view.n_components - 1, 0)
            self.widget_component_slider = IntSlider(value=0,
                                                     max=max_n_components,
                                                     min=0,
                                                     description='component')
            self.widget_component_slider._ngl_name = 'component_slider'

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

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

            self.widget_component_slider.layout.width = default.DEFAULT_SLIDER_WIDTH
            self.widget_repr_slider.layout.width = default.DEFAULT_SLIDER_WIDTH
            self.widget_component_dropdown.layout.width = self.widget_component_dropdown.max_width = default.DEFAULT_TEXT_WIDTH

            # turn off for now
            self.widget_component_dropdown.layout.display = 'none'
            self.widget_component_dropdown.description = ''

            # self.widget_accordion_repr_parameters = Accordion()
            self.widget_accordion_repr_parameters = Tab()
            self.widget_repr_parameters = self._make_widget_repr_parameters(
                self.widget_component_slider, self.widget_repr_slider,
                self.widget_repr_name)
            self.widget_accordion_repr_parameters.children = [
                self.widget_repr_parameters,
                Box()
            ]
            self.widget_accordion_repr_parameters.set_title(0, 'Parameters')
            self.widget_accordion_repr_parameters.set_title(1, 'Hide')
            self.widget_accordion_repr_parameters.selected_index = 1

            checkbox_reprlist = Checkbox(value=False, description='reprlist')
            checkbox_reprlist._ngl_name = 'checkbox_reprlist'
            self.widget_repr_choices = self._make_repr_name_choices(
                self.widget_component_slider, self.widget_repr_slider)
            self.widget_repr_choices._ngl_name = 'reprlist_choices'

            self.widget_repr_add = self._make_add_widget_repr(
                self.widget_component_slider)

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

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

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

                should_update = (self._real_time_update and old and name
                                 and name in REPRESENTATION_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 on_component_or_repr_slider_value_changed(change):
                self._view._request_repr_parameters(
                    component=self.widget_component_slider.value,
                    repr_index=self.widget_repr_slider.value)
                self.widget_component_dropdown.options = tuple(
                    self._view._ngl_component_names)

                if self.widget_accordion_repr_parameters.selected_index >= 0:
                    self.widget_repr_parameters.name = self.widget_repr_name.value
                    self.widget_repr_parameters.repr_index = self.widget_repr_slider.value
                    self.widget_repr_parameters.component_index = self.widget_component_slider.value

            def on_repr_selection_value_changed(change):
                if self._real_time_update:
                    component = self.widget_component_slider.value
                    repr_index = self.widget_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:
                    self.widget_component_slider.value = self._view._ngl_component_names.index(
                        choice)

            self.widget_component_dropdown.observe(
                on_change_component_dropdown, names='value')

            self.widget_repr_slider.observe(
                on_component_or_repr_slider_value_changed, names='value')
            self.widget_component_slider.observe(
                on_component_or_repr_slider_value_changed, names='value')
            self.widget_repr_name.observe(on_repr_name_text_value_changed,
                                          names='value')
            repr_selection.observe(on_repr_selection_value_changed,
                                   names='value')

            self.widget_repr_control_buttons = self._make_button_repr_control(
                self.widget_component_slider, self.widget_repr_slider,
                repr_selection)

            blank_box = Box([Label("")])

            all_kids = [
                self.widget_repr_control_buttons, blank_box,
                self.widget_repr_add, self.widget_component_dropdown,
                self.widget_repr_name, repr_selection,
                self.widget_component_slider, self.widget_repr_slider,
                self.widget_repr_choices, self.widget_accordion_repr_parameters
            ]

            vbox = VBox(all_kids)

            self._view._request_repr_parameters(
                component=self.widget_component_slider.value,
                repr_index=self.widget_repr_slider.value)

            self.widget_repr = _relayout_master(vbox, width='100%')

            self._refresh(self.widget_component_slider,
                          self.widget_repr_slider)

            setattr(self.widget_repr, "_saved_widgets", [])
            for _box in self.widget_repr.children:
                if hasattr(_box, 'children'):
                    for kid in _box.children:
                        self.widget_repr._saved_widgets.append(kid)

            return self.widget_repr
Exemple #13
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])
Exemple #14
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
Exemple #15
0
    def _make_widget_repr(self):
        self.widget_repr_name = Text(value='', description='representation')
        self.widget_repr_name._ngl_name = 'repr_name_text'
        repr_selection = Text(value=' ', description='selection')
        repr_selection._ngl_name = 'repr_selection'
        repr_selection.width = self.widget_repr_name.width = default.DEFAULT_TEXT_WIDTH 

        max_n_components = max(self._view.n_components-1, 0)
        self.widget_component_slider = IntSlider(value=0, max=max_n_components, min=0, description='component')
        self.widget_component_slider._ngl_name = 'component_slider'

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

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

        self.widget_component_slider.layout.width = default.DEFAULT_SLIDER_WIDTH
        self.widget_repr_slider.layout.width = default.DEFAULT_SLIDER_WIDTH
        self.widget_component_dropdown.layout.width = self.widget_component_dropdown.max_width = default.DEFAULT_TEXT_WIDTH

        # turn off for now
        self.widget_component_dropdown.layout.display = 'none'
        self.widget_component_dropdown.description = ''

        # self.widget_accordion_repr_parameters = Accordion()
        self.widget_accordion_repr_parameters = Tab()
        self.widget_repr_parameters =  self._make_widget_repr_parameters(self.widget_component_slider,
                self.widget_repr_slider,
                self.widget_repr_name)
        self.widget_accordion_repr_parameters.children = [self.widget_repr_parameters, Box()]
        self.widget_accordion_repr_parameters.set_title(0, 'Parameters')
        self.widget_accordion_repr_parameters.set_title(1, 'Hide')
        self.widget_accordion_repr_parameters.selected_index = 1
        
        checkbox_reprlist = Checkbox(value=False, description='reprlist')
        checkbox_reprlist._ngl_name = 'checkbox_reprlist'
        self.widget_repr_choices = self._make_repr_name_choices(self.widget_component_slider,
                self.widget_repr_slider)
        self.widget_repr_choices._ngl_name = 'reprlist_choices'

        self.widget_repr_add = self._make_add_widget_repr(self.widget_component_slider)

        def on_update_checkbox_reprlist(change):
            self.widget_repr_choices.visible= change['new']
        checkbox_reprlist.observe(on_update_checkbox_reprlist, names='value')

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

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

            if should_update:
                component=self.widget_component_slider.value
                repr_index=self.widget_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 on_component_or_repr_slider_value_changed(change):
            self._view._request_repr_parameters(component=self.widget_component_slider.value,
                                                repr_index=self.widget_repr_slider.value)
            self.widget_component_dropdown.options = tuple(self._view._ngl_component_names)

            if self.widget_accordion_repr_parameters.selected_index >= 0:
                self.widget_repr_parameters.name = self.widget_repr_name.value
                self.widget_repr_parameters.repr_index = self.widget_repr_slider.value
                self.widget_repr_parameters.component_index = self.widget_component_slider.value

        def on_repr_selection_value_changed(change):
            if self._real_time_update:
                component = self.widget_component_slider.value
                repr_index = self.widget_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:
                 self.widget_component_slider.value = self._view._ngl_component_names.index(choice)

        self.widget_component_dropdown.observe(on_change_component_dropdown, names='value')

        self.widget_repr_slider.observe(on_component_or_repr_slider_value_changed, names='value')
        self.widget_component_slider.observe(on_component_or_repr_slider_value_changed, names='value')
        self.widget_repr_name.observe(on_repr_name_text_value_changed, names='value')
        repr_selection.observe(on_repr_selection_value_changed, names='value')

        self.widget_repr_control_buttons = self._make_button_repr_control(self.widget_component_slider,
        self.widget_repr_slider, repr_selection)

        blank_box = Box([Label("")])

        all_kids = [self.widget_repr_control_buttons,
                    blank_box,
                    self.widget_repr_add,
                    self.widget_component_dropdown,
                    self.widget_repr_name,
                    repr_selection,
                    self.widget_component_slider,
                    self.widget_repr_slider,
                    self.widget_repr_choices,
                    self.widget_accordion_repr_parameters
        ]

        vbox = VBox(all_kids)

        self._view._request_repr_parameters(component=self.widget_component_slider.value,
            repr_index=self.widget_repr_slider.value)

        self.widget_repr = _relayout_master(vbox, width='100%')

        self._refresh(self.widget_component_slider, self.widget_repr_slider)

        setattr(self.widget_repr, "_saved_widgets", [])
        for _box in self.widget_repr.children:
            if hasattr(_box, 'children'):
                for kid in _box.children:
                    self.widget_repr._saved_widgets.append(kid)

        return self.widget_repr
Exemple #16
0
class NGLDisplay:
    """Structure display class

    Provides basic structure/trajectory display
    in the notebook and optional gui which can be used to enhance its
    usability.  It is also possible to extend the functionality of the
    particular instance of the viewer by adding further widgets
    manipulating the structure.
    """
    def __init__(self, atoms, xsize=500, ysize=500):
        import nglview
        from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox
        self.atoms = atoms
        if isinstance(atoms[0], Atoms):
            # Assume this is a trajectory or struct list
            self.view = nglview.show_asetraj(atoms)
            self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1)
            self.frm.observe(self._update_frame)
            self.struct = atoms[0]
        else:
            # Assume this is just a single structure
            self.view = nglview.show_ase(atoms)
            self.struct = atoms
            self.frm = None

        self.colors = {}
        self.view._remote_call('setSize', target='Widget',
                               args=['%dpx' % (xsize,), '%dpx' % (ysize,)])
        self.view.add_unitcell()
        self.view.add_spacefill()
        self.view.camera = 'orthographic'
        self.view.update_spacefill(radiusType='covalent', scale=0.7)
        self.view.center()

        self.asel = Dropdown(options=['All'] +
                             list(set(self.struct.get_chemical_symbols())),
                             value='All', description='Show')

        self.rad = FloatSlider(value=0.8, min=0.0, max=1.5, step=0.01,
                               description='Ball size')

        self.asel.observe(self._select_atom)
        self.rad.observe(self._update_repr)

        wdg = [self.asel, self.rad]
        if self.frm:
            wdg.append(self.frm)

        self.gui = HBox([self.view, VBox(wdg)])
        # Make useful shortcuts for the user of the class
        self.gui.view = self.view
        self.gui.control_box = self.gui.children[1]
        self.gui.custom_colors = self.custom_colors

    def _update_repr(self, chg=None):
        self.view.update_spacefill(radiusType='covalent', scale=self.rad.value)

    def _update_frame(self, chg=None):
        self.view.frame = self.frm.value
        return

    def _select_atom(self, chg=None):
        sel = self.asel.value
        self.view.remove_spacefill()
        for e in set(self.struct.get_chemical_symbols()):
            if (sel == 'All' or e == sel):
                if e in self.colors:
                    self.view.add_spacefill(selection='#' + e,
                                            color=self.colors[e])
                else:
                    self.view.add_spacefill(selection='#' + e)
        self._update_repr()

    def custom_colors(self, clr=None):
        """
        Define custom colors for some atoms. Pass a dictionary of the form
        {'Fe':'red', 'Au':'yellow'} to the function.
        To reset the map to default call the method without parameters.
        """
        if clr:
            self.colors = clr
        else:
            self.colors = {}
        self._select_atom()
    def initialize(self,
                   model_state,
                   measurements=None,
                   true_state=None,
                   landmarks=None,
                   robot_cov=None,
                   marker_cov=None,
                   add_aruco=False,
                   dt_data=0.2):
        self.lock = thrd.Lock()

        self.initialized = False
        self.measurements = measurements
        self.landmarks = landmarks
        self.marker_cov = marker_cov
        self.true_state = true_state
        self.robot_cov = robot_cov
        self.paused = False
        self.cur_frame = 0
        self.dt_data = dt_data
        self.dt_render = dt_data
        self.state = model_state
        self.aruco_markers = {}

        # Initialize figure
        fig = plt.figure(constrained_layout=True, figsize=(14, 5))
        gs = fig.add_gridspec(2, 2)
        ax = fig.add_subplot(gs[:, 0])
        ax2 = fig.add_subplot(gs[0, 1])
        ax2.set_xlim([0, 500])
        ax2.set_ylim([-5, 5])
        ax2.set_title('State Error')
        ax2.set_xlabel('Time')
        ax2.set_ylabel('Difference between true\nand predicted value')
        ax3 = fig.add_subplot(gs[1, 1])
        ax3.set_title('Marker Error')
        ax3.set_xlabel('Time')
        ax3.set_ylabel('Avg. difference between\ntrue and predicted value')
        ax3.set_xlim([0, 500])
        ax3.set_ylim([-5, 5])

        ax.set_xlim([-4, -1.5])
        ax.set_ylim([-3.5, -1.5])
        ax.tick_params(axis='both', which='major', labelsize=7)
        ax.set_title('Overhead View')
        ax.set_xlabel('X (m)', weight='bold')
        ax.set_ylabel('Y (m)', weight='bold')

        self.figure = fig

        # Plot ground truth trajectory
        ax.plot(self.true_state[:, 0],
                self.true_state[:, 1],
                c='r',
                lw=1,
                label='True state (from data)')

        # Plot current model state
        self.line, = ax.plot(self.state[0, 0],
                             self.state[0, 1],
                             c='b',
                             lw=1,
                             label='Predicted state (model)')

        # Plot position error
        self.pos_x_error, = ax2.plot(0,
                                     self.true_state[0, 0] - self.state[0, 0],
                                     label='X-coordinate')
        self.pos_y_error, = ax2.plot(0,
                                     self.true_state[0, 1] - self.state[0, 1],
                                     label='Y-coordinate')
        ax2.legend(loc='best')

        self.marker_x_error, = ax3.plot(0, 0, label='X-coordinate')
        self.marker_y_error, = ax3.plot(0, 0, label='Y-coordinate')
        ax3.legend(loc='best')

        ax.legend(loc='upper right')
        # Create Robot Axes
        self.robot_ax = []
        self.robot_ax.append(
            FancyArrowPatch((0, 0), (0.15, 0), mutation_scale=8, color='red'))
        self.robot_ax.append(
            FancyArrowPatch((0, 0), (0, 0.15), mutation_scale=8,
                            color='green'))

        # Apply translation and rotation as specified by current robot state
        cos_theta, sin_theta = np.cos(self.state[0, 2]), np.sin(self.state[0,
                                                                           2])
        Tw_r = np.eye(3)
        Tw_r[0:2, 2] = self.state[0, :2]
        Tw_r[0:2, 0:2] = [[cos_theta, -sin_theta], [sin_theta, cos_theta]]
        Tw_r_obj = transforms.Affine2D(Tw_r)
        self.ax_trans = ax.transData
        self.robot_ax[0].set_transform(Tw_r_obj + self.ax_trans)
        self.robot_ax[1].set_transform(self.robot_ax[0].get_transform())
        ax.add_patch(self.robot_ax[0])
        ax.add_patch(self.robot_ax[1])

        if add_aruco:
            marker_files = [
                filename for filename in os.listdir('Support/images')
                if filename.startswith("M")
            ]
            marker_world_width = 0.3
            for i, filename in enumerate(marker_files):
                fprts = filename.split('_')
                mp = np.array([float(fprts[1]), float(fprts[2])])
                mi = cv2.imread('Support/images/' + filename)
                ext = [mp[0]-marker_world_width/2,mp[0]+marker_world_width/2,\
                mp[1]-marker_world_width/2,mp[1]+marker_world_width/2]
                ax.imshow(mi, extent=ext)
                ax.annotate(str(i), (mp[0], mp[1]), color='red', weight='bold')
                self.aruco_markers[int(fprts[0][-1])] = mp

        #Set up to plot measurements
        if self.measurements is not None:
            self.marker_lines = []
            self.marker_lables = []
            self.marker_scatter = ax.scatter(np.zeros((10, 1)),
                                             np.zeros((10, 1)),
                                             color='lime')
            for i in range(10):
                ln, = ax.plot(np.zeros((2, 1)),
                              np.zeros((2, 1)),
                              color='yellow',
                              alpha=0.5)
                self.marker_lines.append(ln)
                an = ax.annotate(str(i), (-3, -2.5),
                                 color='green',
                                 weight='bold')
                self.marker_lables.append(an)

        #Set up to plot added landmarks
        if self.landmarks is not None:
            self.landmarks_scatter = ax.scatter(self.landmarks[0][0, :],
                                                self.landmarks[0][1, :],
                                                s=80,
                                                color='red')

        if self.marker_cov is not None:
            num_landmarks = self.landmarks[-1].shape[1]
            self.marker_ells = []
            for i in range(num_landmarks):
                el = Ellipse((0, 0),
                             width=0.3,
                             height=0.3,
                             angle=0,
                             facecolor='none',
                             edgecolor='blue')
                self.marker_ells.append(el)
                ax.add_patch(el)
            for i in range(self.landmarks[self.cur_frame].shape[1]):
                self.marker_ells[i].set_center(
                    (self.landmarks[self.cur_frame][0, i],
                     self.landmarks[self.cur_frame][1, i]))

        #Set up ellipsoid to draw robot covariance
        if self.robot_cov is not None:
            cov = self.robot_cov[0, :, :]
            a = cov[0, 0]
            b = cov[0, 1]
            c = cov[1, 0]
            d = cov[1, 1]
            B = -(a + d)
            C = (a * d - b * c)
            lam1 = (-B + np.sqrt(B**2 - 4 * C)) / 2
            lam2 = (-B - np.sqrt(B**2 - 4 * C)) / 2
            v1 = np.array([[lam1 - d], [c]])
            self.robo_ell = Ellipse(
                (self.state[0, 0], self.state[0, 1]),
                width=lam1,
                height=lam2,
                angle=np.rad2deg(np.arccos(v1[0] / np.linalg.norm(v1))))
            self.robo_ell.set_facecolor('none')
            self.robo_ell.set_edgecolor('blue')
            ax.add_patch(self.robo_ell)

        btn_play = widgets.Button(description='Play/Pause',
                                  layout=Layout(flex='1 1 0%', width='auto'),
                                  button_style='success')
        btn_play.on_click(self.pause)

        btn_prev = widgets.Button(description='<<',
                                  layout=Layout(flex='0.3 1 0%', width='auto'),
                                  button_style='warning')
        btn_prev.on_click(self.prv)

        btn_next = widgets.Button(description='>>',
                                  layout=Layout(flex='0.3 1 0%', width='auto'),
                                  button_style='warning')
        btn_next.on_click(self.nxt)

        controls = [
            IntSlider(description='Frame: ',
                      layout=Layout(flex='3 1 0%', width='auto'),
                      min=0,
                      max=(model_state.shape[0] - 1)), btn_prev, btn_play,
            btn_next
        ]

        self.slider = controls[0]
        self.slider.observe(self.slider_change, names='value')

        box_layout = Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            width='70%')
        display(Box(children=controls, layout=box_layout))

        if not self.is_alive():
            self.start()

        self.initialized = True
Exemple #18
0
    return [create_image(grayscott) for i in tqdm(range(n))]
    
frames = create_frames(500, numpy_grayscott)

# +
from ipywidgets import interact, IntSlider

def display_sequence(iframe):
    
    return Image.fromarray(frames[iframe])
    
interact(display_sequence, 
         iframe=IntSlider(min=0,
                          max=len(frames)-1,
                          step=1,
                          value=0, 
                          continuous_update=True))
# -

import imageio
frames_scaled = [np.uint8(255 * frame) for frame in frames]
imageio.mimsave('movie.gif', frames_scaled, format='gif', fps=60)

# ![grayscott](movie.gif "grayscott")

# ## References
#
# - [Reaction-Diffusion by the Gray-Scott Model: Pearson's Parametrization](https://mrob.com/pub/comp/xmorphia/)

# ## Cython
Exemple #19
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()
Exemple #20
0
def show_opt_team(player_gw_next_eps_ext: DF,
                  max_budget: float,
                  ctx: Context,
                  def_budget: float = None):
    def get_message(optimise_team_on, optimise_sel_on, budget,
                    expens_player_count, include, exclude, risk,
                    recommend) -> None:
        message = '<span style="margin-right: 30px">'

        if recommend is not None:
            message += f'Recommend <strong>{recommend}</strong> transfer(s) with the highest <strong>{optimise_team_on}</strong> '
        else:
            message += f'Create a team with the highest <strong>{optimise_team_on}</strong> '

        message += f'within the budget of <strong>£{budget:.1f}m</strong> biasing the team towards <strong>{expens_player_count}</strong> more expensive player(s) ' + \
                   f'and taking <strong>{risk:.0%}</strong> risk '

        if len(include) > 0 and len(exclude) == 0:
            message += f'while including <strong>{",".join(include)}</strong> '
        elif len(include) == 0 and len(exclude) > 0:
            message += f'while excluding <strong>{",".join(exclude)}</strong> '
        elif len(include) > 0 and len(exclude) > 0:
            message += f'while including <strong>{",".join(include)}</strong> and excluding <strong>{",".join(exclude)}</strong> '

        message += f'and optimise the selection for <strong>{optimise_sel_on}</strong>.</span>'

        return message

    def get_players(players_text: str) -> Tuple:
        return tuple([v.strip() for v in players_text.split(',')
                      ]) if players_text != '' else ()

    def get_args():
        return dict(
            recommend=(recommend_slider.value if has_in_team else None),
            optimise_team_on='Expected Points ' + opt_for_dropdown.value,
            budget=budget_slider.value,
            optimise_sel_on='Expected Points ' + sel_for_dropdown.value,
            expens_player_count=expens_player_slider.value,
            include=get_players(include_text.value),
            exclude=get_players(exclude_text.value),
            risk=risk_slider.value)

    def validate_include_exclude(df, include_exclude,
                                 include_exclude_text) -> None:
        include_exclude_lower = [v.lower() for v in include_exclude]
        if not set(
                df['Name'].str.lower().values) >= set(include_exclude_lower):
            invalid_include_exclude = [
                v for v in include_exclude
                if v.lower() in (set(include_exclude_lower) -
                                 set(df["Name"].str.lower().values))
            ]
            if len(invalid_include_exclude) == 1:
                raise ValueError(
                    f'{invalid_include_exclude[0]} in {include_exclude_text} is not a valid player name.'
                )
            else:
                raise ValueError(
                    f'{", ".join(invalid_include_exclude)} in {include_exclude_text} are not valid player names.'
                )

    @debounce(1)
    def on_value_change(change):
        args = get_args()
        error_html.value = ''
        try:
            validate_include_exclude(player_gw_next_eps_ext, args['include'],
                                     'Include')
            validate_include_exclude(player_gw_next_eps_ext, args['exclude'],
                                     'Exclude')

            message_html.value = get_message(**args)
            optimise_team()
            error_html.value = ''
        except Exception as e:
            error_html.value = f'<div class="alert alert-danger">{e}</div>'

    def optimise_team():
        error_html.value = f'<div class="alert alert-success">Optimising ...</div>'
        with out:
            out.clear_output()
            summary = display_optimal_team(players_df=player_gw_next_eps_ext,
                                           ctx=ctx,
                                           formation=(2, 5, 5, 3),
                                           **get_args())

            display(summary)

    has_in_team = 'In Team?' in player_gw_next_eps_ext.columns
    horizons = get_horizons(player_gw_next_eps_ext)

    if def_budget is None:
        def_budget = max_budget

    # Define the selector controls
    opt_for_dropdown = Dropdown(description='Optimise for',
                                options=horizons,
                                value=ctx.def_next_gws)
    sel_for_dropdown = Dropdown(description='Select for', options=horizons)
    budget_slider = FloatSlider(value=def_budget,
                                min=0,
                                max=max_budget,
                                step=0.1,
                                description='Budget',
                                continuous_update=True,
                                readout_format='.1f')
    expens_player_label = Label('Expensive players')
    expens_player_slider = IntSlider(value=15,
                                     min=1,
                                     max=15,
                                     step=1,
                                     continuous_update=True,
                                     readout_format='.0f')
    include_text = Text(description='Include',
                        placeholder='Comma separated player names')
    exclude_text = Text(description='Exclude',
                        placeholder='Comma separated player names')
    risk_slider = FloatSlider(value=0.2,
                              min=0,
                              max=1,
                              step=0.1,
                              description='Risk',
                              continuous_update=True,
                              readout_format='.0%')
    recommend_slider = IntSlider(value=1,
                                 min=0,
                                 max=11,
                                 step=1,
                                 description='Recommend',
                                 continuous_update=True,
                                 readout_format='.0f')

    message_html = HTML()
    error_html = HTML(layout=Layout(flex='1 1 0%', width='auto'))

    hbox_layout = Layout(display='flex',
                         flex_flow='row',
                         align_items='stretch',
                         width='100%')

    hboxes = []
    hboxes += [
        HBox([opt_for_dropdown, sel_for_dropdown] +
             ([recommend_slider] if has_in_team else []),
             layout=hbox_layout)
    ]
    hboxes += [
        HBox([include_text, exclude_text, risk_slider], layout=hbox_layout)
    ]
    hboxes += [
        HBox([budget_slider, expens_player_label, expens_player_slider],
             layout=hbox_layout)
    ]

    for hbox in hboxes:
        for widget in hbox.children:
            widget.observe(on_value_change, names='value')

    hboxes += [HBox([message_html])]
    hboxes += [HBox([error_html])]
    out = Output()

    on_value_change(None)

    return VBox(hboxes + [out])
Exemple #21
0
            latex_string += r'\\'
            latex_string += '\n'
    latex_string += r'\end{array}\right]$'
    return display_string_as_html_in_div(latex_string, div_id=div_id)


if __name__ == "__main__":

    def test_widgets(a, b, c, d, e):
        print("a=", a, "b=", b, "c=", c, "d=", d, "e=", e)

    ob_interactive = interactive(
        test_widgets,
        a=IntSlider(min=3,
                    max=51,
                    step=2,
                    value=17,
                    description='xxxxxxxxxxxxxxxxxxxxxxxxxxxx'),
        b=FloatSlider(min=3,
                      max=51,
                      step=2,
                      value=19,
                      description='zzzzzzzzzzzzz'),
        c=Checkbox(description="this is a check box"),
        d=Label(value="This is a label"),
        e=Dropdown(options=["Option 1", "Option 2", "Option 3"],
                   value="Option 1",
                   description="DropDown",
                   continuous_update=False))
    if in_ipython_flag:
        print("Testing arrange_widgets_in_grid")
def view_binding_site(pdbIds=None, groups=None, chains=None, distance=3.0):
    '''A wrapper function that zooms in to a group of a protein structure and highlight
    its neighbors within a certain distance.

    Parameters
    ----------
    pdbIds : list, optional 
       A list of PDBIDs to display
    groups : list, optional
       A list of groups to center at for each protein structure
    chains : list, optional
       A list of chains specified for each protein structure.  
       If no chains is specified, chain 'A' will be default to
       all structures.
    cutoffDistance : float, optional
       The cutoff distance use the find the neighbors of specified group

    '''

    if pdbIds is None or groups is None:
        raise ValueError("PdbIds and groups need to be specified")

    if len(pdbIds) != len(groups):
        raise ValueError(
            "Number of structures should match with number of groups")

    if type(pdbIds) == str and groups == str:
        pdbIds, groups = [pdbIds], [groups]

    if chains is None:
        chains = ['A'] * len(pdbIds)

    def view3d(i=0):
        '''Simple structure viewer that zooms into a specified group and highlight
        its neighbors

        Parameters
        ----------
            i (int): index of the protein if a list of PDBids
        '''

        print(
            f"PDB: {pdbIds[i]}, group: {groups[i]}, chain: {chains[i]}, cutoffDistance: {distance}"
        )

        if type(groups[i]) == int:
            center = {'resi': groups[i], 'chain': chains[i]}
            neighbors = {
                'resi': groups[i],
                'chain': chains[i],
                'byres': 'true',
                'expand': distance
            }
        else:
            center = {'resn': groups[i], 'chain': chains[i]}
            neighbors = {
                'resn': groups[i],
                'chain': chains[i],
                'byres': 'true',
                'expand': distance
            }

        viewer = py3Dmol.view(query='pdb:' + pdbIds[i])
        viewer.setStyle(neighbors, {'stick': {}})
        viewer.setStyle(center, {'sphere': {'colorscheme': 'orangeCarbon'}})
        viewer.zoomTo(neighbors)

        return viewer.show()

    s_widget = IntSlider(min=0,
                         max=len(pdbIds) - 1,
                         description='Structure',
                         continuous_update=False)
    return interact(view3d, i=s_widget)
Exemple #23
0
def plot(vtkfile_path, color_attribute_name, color_map=get_cmap('viridis')):
    ''' Generate a k3d Plot and associated controls for VTK data from file

    :param vtkfile_path: the path to load vtk data from. Can be a single .vtu or a collection
    :param color_attribute_name: which data array from vtk to use for plot coloring
    :param color_map: a Matplotlib Colormap object or a K3D array((step, r, g, b))
    :return: the generated Plot object
    '''
    if isinstance(color_map, Colormap):
        color_map = [(x, *color_map(x)[:3]) for x in np.linspace(0, 1, 256)]

    data = read_vtkfile(vtkfile_path)
    size = len(data)

    # getbounds: (xmin, xmax, ymin, ymax, zmin, zmax)
    all_bounds = np.stack([p[1].GetBounds() for p in data])
    combined_bounds = np.array([
        np.min(all_bounds[:, 0]),
        np.min(all_bounds[:, 2]),
        np.min(all_bounds[:, 4]),
        np.max(all_bounds[:, 1]),
        np.max(all_bounds[:, 3]),
        np.max(all_bounds[:, 5])
    ])

    vtkplot = VTKPlot(data,
                      color_attribute_name=color_attribute_name,
                      grid_auto_fit=False,
                      camera_auto_fit=False,
                      color_map=color_map,
                      grid=combined_bounds)
    # display needs to have been called before changing camera/grid_visible
    vtkplot.display()
    # could be replaced with testing if the widget is'ready'
    time.sleep(0.5)
    vtkplot.grid_visible = False
    try:
        vtkplot.menu_visibility = False
    except AttributeError:
        pass  # k3d < 2.5.6
    # guesstimate
    fov_angle = 30
    absx = np.abs(combined_bounds[0] - combined_bounds[3])
    c_dist = np.sin((90 - fov_angle) * np.pi /
                    180) * absx / (2 * np.sin(fov_angle * np.pi / 180))
    xhalf = (combined_bounds[0] + combined_bounds[3]) / 2
    yhalf = (combined_bounds[1] + combined_bounds[4]) / 2
    zhalf = (combined_bounds[2] + combined_bounds[5]) / 2
    # camera[posx, posy, posz, targetx, targety, targetz, upx, upy, upz]
    vtkplot.camera = (xhalf, yhalf, zhalf + c_dist, xhalf, yhalf, zhalf, 0, 1,
                      0)

    if size > 1:
        play = Play(min=0,
                    max=size - 1,
                    step=1,
                    value=0,
                    description='Timestep:')
        interact(idx=play).widget(vtkplot._goto_idx)
        slider = IntSlider(min=0,
                           max=size - 1,
                           step=1,
                           value=0,
                           description='Timestep:')
        interact(idx=slider).widget(vtkplot._goto_idx)
        widgets.jslink((play, 'value'), (slider, 'value'))
        hbox = widgets.HBox([play, slider])
        IPython.display.display(hbox)

    return vtkplot
    def interact_ometif(self):
        """Interactor for visualizing the ome.tif file at low resolution and an associated region."""
        def _interact_ometif(frame, left, top, width, height):
            button, text = _create_button_text_display('ometif_region_seg.png')

            # get the region at 1.25x resolution for frame 0
            lr_im = self.ts.getRegion(
                format=large_image.tilesource.TILE_FORMAT_NUMPY,
                scale={'magnification': 1.25},
                frame=self.chnames[frame])[0][:, :, 0]

            fig, ax = plt.subplots(ncols=2, figsize=(15, 7))

            ax[0].imshow(lr_im, cmap='gray')
            ax[0].set_title(f'ome.tif channel {frame} at 1.25X magnification',
                            fontsize=18)

            # get the region and reset the fields of regions....is this the best way to do it?
            region = {
                'left': left,
                'top': top,
                'width': width,
                'height': height
            }
            self.region = region

            self.region_masks = {}
            for mask_name, mask_filepath in self.masks_dict.items():
                mask = fix_segmentation_mask(
                    imread(mask_filepath)[region['top']:region['top'] +
                                          region['height'],
                                          region['left']:region['left'] +
                                          region['width'], ])
                self.region_masks[mask_name] = mask

            reg_im = self.ts.getRegion(
                format=large_image.tilesource.TILE_FORMAT_NUMPY,
                region=region,
                frame=self.chnames[frame])[0][:, :, 0]

            self.region_im = reg_im

            ax[1].imshow(reg_im, cmap='gray')
            ax[1].set_title('Image region at full magnification', fontsize=18)
            ax[1].xaxis.set_visible(False)
            ax[1].yaxis.set_visible(False)
            plt.suptitle(
                'View OME.TIF at low magnification and select region to view at full mag',
                fontweight='bold',
                fontsize=20)
            fig.tight_layout(rect=[0, 0, 1, .9])
            plt.show()

            button.on_click(
                partial(self.on_button_clicked,
                        text_widget=text,
                        fig_to_save=fig))
            display(widgets.HBox([text, button]))

        chnames = list(self.chnames.keys())
        a = Dropdown(options=chnames,
                     value=chnames[0],
                     description='Channel:',
                     style=DESC_STYLES)
        b = IntSlider(min=0,
                      max=self.ts.getMetadata()['sizeX'],
                      value=self.region['left'],
                      description='Region left coord:',
                      style=DESC_STYLES,
                      continuous_update=False)
        c = IntSlider(min=0,
                      max=self.ts.getMetadata()['sizeY'],
                      value=self.region['top'],
                      description='Region top coord:',
                      style=DESC_STYLES,
                      continuous_update=False)
        d = IntSlider(min=100,
                      max=5000,
                      value=self.region['width'],
                      description='Region width:',
                      style=DESC_STYLES,
                      continuous_update=False)
        e = IntSlider(min=100,
                      max=5000,
                      value=self.region['height'],
                      description='Region height:',
                      style=DESC_STYLES,
                      continuous_update=False)

        row1 = widgets.HBox([a])
        row2 = widgets.HBox([b, d])
        row3 = widgets.HBox([c, e])
        ui = widgets.VBox([row1, row2, row3])

        out = widgets.interactive_output(_interact_ometif, {
            'frame': a,
            'left': b,
            'top': c,
            'width': d,
            'height': e
        })

        display(ui, out)
Exemple #25
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
Exemple #26
0
def visualize_patch(grid,
                    U,
                    bounding_box=([0, 0], [1, 1]),
                    codim=2,
                    title=None,
                    legend=None,
                    separate_colorbars=False,
                    rescale_colorbars=False,
                    columns=2):
    """Visualize scalar data associated to a two-dimensional |Grid| as a patch plot.

    The grid's |ReferenceElement| must be the triangle or square. The data can either
    be attached to the faces or vertices of the grid.

    Parameters
    ----------
    grid
        The underlying |Grid|.
    U
        |VectorArray| of the data to visualize. If `len(U) > 1`, the data is visualized
        as a time series of plots. Alternatively, a tuple of |VectorArrays| can be
        provided, in which case a subplot is created for each entry of the tuple. The
        lengths of all arrays have to agree.
    bounding_box
        A bounding box in which the grid is contained.
    codim
        The codimension of the entities the data in `U` is attached to (either 0 or 2).
    title
        Title of the plot.
    legend
        Description of the data that is plotted. Most useful if `U` is a tuple in which
        case `legend` has to be a tuple of strings of the same length.
    separate_colorbars
        If `True`, use separate colorbars for each subplot.
    rescale_colorbars
        If `True`, rescale colorbars to data in each frame.
    columns
        The number of columns in the visualizer GUI in case multiple plots are displayed
        at the same time.
    """

    assert isinstance(U, VectorArrayInterface) \
        or (isinstance(U, tuple)
            and all(isinstance(u, VectorArrayInterface) for u in U)
            and all(len(u) == len(U[0]) for u in U))
    U = (U.to_numpy().astype(np.float64, copy=False),) if isinstance(U, VectorArrayInterface) else \
        tuple(u.to_numpy().astype(np.float64, copy=False) for u in U)

    if not config.HAVE_MATPLOTLIB:
        raise ImportError('cannot visualize: import of matplotlib failed')
    if not config.HAVE_IPYWIDGETS and len(U[0]) > 1:
        raise ImportError('cannot visualize: import of ipywidgets failed')

    if isinstance(legend, str):
        legend = (legend, )
    assert legend is None or isinstance(legend,
                                        tuple) and len(legend) == len(U)
    if len(U) < 2:
        columns = 1

    class Plot:
        def __init__(self):
            if separate_colorbars:
                if rescale_colorbars:
                    self.vmins = tuple(np.min(u[0]) for u in U)
                    self.vmaxs = tuple(np.max(u[0]) for u in U)
                else:
                    self.vmins = tuple(np.min(u) for u in U)
                    self.vmaxs = tuple(np.max(u) for u in U)
            else:
                if rescale_colorbars:
                    self.vmins = (min(np.min(u[0]) for u in U), ) * len(U)
                    self.vmaxs = (max(np.max(u[0]) for u in U), ) * len(U)
                else:
                    self.vmins = (min(np.min(u) for u in U), ) * len(U)
                    self.vmaxs = (max(np.max(u) for u in U), ) * len(U)

            import matplotlib.pyplot as plt

            rows = int(np.ceil(len(U) / columns))
            self.figure = figure = plt.figure()

            self.plots = plots = []
            axes = []
            for i, (vmin, vmax) in enumerate(zip(self.vmins, self.vmaxs)):
                ax = figure.add_subplot(rows, columns, i + 1)
                axes.append(ax)
                plots.append(
                    MatplotlibPatchAxes(figure,
                                        grid,
                                        bounding_box=bounding_box,
                                        vmin=vmin,
                                        vmax=vmax,
                                        codim=codim,
                                        colorbar=separate_colorbars))
                if legend:
                    ax.set_title(legend[i])

            plt.tight_layout()
            if not separate_colorbars:
                figure.colorbar(plots[0].p, ax=axes)

        def set(self, U, ind):
            if rescale_colorbars:
                if separate_colorbars:
                    self.vmins = tuple(np.min(u[ind]) for u in U)
                    self.vmaxs = tuple(np.max(u[ind]) for u in U)
                else:
                    self.vmins = (min(np.min(u[ind]) for u in U), ) * len(U)
                    self.vmaxs = (max(np.max(u[ind]) for u in U), ) * len(U)

            for u, plot, vmin, vmax in zip(U, self.plots, self.vmins,
                                           self.vmaxs):
                plot.set(u[ind], vmin=vmin, vmax=vmax)

    plot = Plot()
    plot.set(U, 0)

    if len(U[0]) > 1:

        from ipywidgets import interact, IntSlider

        def set_time(t):
            plot.set(U, t)

        interact(set_time,
                 t=IntSlider(min=0, max=len(U[0]) - 1, step=1, value=0))

    return plot
Exemple #27
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
Exemple #28
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
Exemple #29
0
    # Pie chart, where the slices will be ordered and plotted counter-clockwise:
    labels = 'Agree', 'Disagree'
    sizes = [np.sum(discrepancyMapping==1),np.sum(discrepancyMapping==0)]

    fig1, ax1 = plt.subplots()
    ax1.pie(sizes,  labels=labels, autopct='%1.3f%%',
        shadow=True, startangle=90)
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
    plt.show()
    
#update the plot via input values     
def update(xOffset, yOffset):
    naieveOceanMaskMoved = np.roll(naieveOceanMask,yOffset,0)
    naieveOceanMaskMoved = np.roll(naieveOceanMaskMoved,xOffset,1)
    plot_mapDiscrepancy(obtainedOceanMask,naieveOceanMaskMoved)

#establish interactivity
interact(update, xOffset=IntSlider(min=-30, max=30, step=1,continuous_update=False),  yOffset=IntSlider(min=-30, max=30, step=1,continuous_update=False))


# It seems that the lowest mismatch percentage you can get is around 17%, which occurs at -28 x offset and -9 y offset.  What accounts for the remaining mismatch?  Part of it likely has to do with how our mask was made (and the threshold value we chose), and that it likely wasnn't entirely perfect.
# 
# One major source of discrepancy is the fact that sea ice is not the color of water, but is not included in the purpose-made land mask we obtained either.  Hence our algorithm considers it "land" (because it is not the color of water), even though the gray colored mask (the provided mask) is specific to land (which ice does not count as).
# 
# Finally, one final source is likely that the two maps, even if they were to have their equator and prime maridian lined up, may not be warped (reshaped from a surface that covers a sphere) in exactly the same way.  Theoretically we could attempt to apply a **nonlinear warp** (we'll come back to this concept in later lessons) to try and align the two images, but this would be beyond the scope of this introduction to digital image representations and masks.

# #### How this relates to neuroimaging
# 
# 
# In the next lesson we will see a more complex version of a mask, one which is not binary, but instead features multiple different categories.  That is, instead of just trying to label one thing (i.e. "water") we will try and use the same general approach to label multiple things.  This capability is something that is used in neuroimaging quite frequently.  For example, we often wish to label particular parts of a neuroimaging scan as being some specific part of the brain (e.g. "frontal lobe", "angular gyrus", or "thalamus" etc.).  We'll explore this possibility in 2D with another map in the next lesson.  In later lessons we'll explicitly look at these "multi category masks" (i.e. **parcellations**) in brains.
def nb_view_patches(Yr,
                    A,
                    C,
                    S,
                    b,
                    f,
                    d1,
                    d2,
                    YrA=None,
                    image_neurons=None,
                    thr=0.99,
                    denoised_color=None,
                    cmap='jet'):
    """
    Interactive plotting utility for ipython notebook

    Args:
        Yr: np.ndarray
            movie

        A,C,b,f: np.ndarrays
            outputs of matrix factorization algorithm

        d1,d2: floats
            dimensions of movie (x and y)

        YrA:   np.ndarray
            ROI filtered residual as it is given from update_temporal_components
            If not given, then it is computed (K x T)

        image_neurons: np.ndarray
            image to be overlaid to neurons (for instance the average)

        thr: double
            threshold regulating the extent of the displayed patches

        denoised_color: string or None
            color name (e.g. 'red') or hex color code (e.g. '#F0027F')

        cmap: string
            name of colormap (e.g. 'viridis') used to plot image_neurons
    """

    # PREPROCESSING
    nr, T = C.shape
    nA2 = np.ravel(np.power(A,
                            2).sum(0)) if type(A) == np.ndarray else np.ravel(
                                A.power(2).sum(0))
    b = np.squeeze(b)
    f = np.squeeze(f)
    if YrA is None:
        Y_r = np.array(
            spdiags(old_div(1, nA2), 0, nr, nr) *
            (A.T * np.matrix(Yr) -
             (A.T * np.matrix(b[:, np.newaxis])) * np.matrix(f[np.newaxis]) -
             A.T.dot(A) * np.matrix(C)) + C)
    else:
        Y_r = C + YrA

    x = np.arange(T)
    if image_neurons is None:
        image_neurons = A.mean(1).reshape((d1, d2), order='F')

    coors = get_contours(A, (d1, d2), thr)
    cc1 = [cor['coordinates'][:, 0] for cor in coors]
    cc2 = [cor['coordinates'][:, 1] for cor in coors]
    c1 = cc1[0]
    c2 = cc2[0]

    # PLOTTING
    fig, axes = plt.subplots(2)
    axes[0].imshow(image_neurons, cmap='gray')
    axes[0].set_title('Neural map')
    axes[1].plot(C[0], label='C: raw traces', c='blue')
    axes[1].plot(Y_r[0], label='Y_r: residuals', c='red')
    axes[1].plot(S[0], label='S: deconvolved activity', c='green')
    plt.legend()
    axes[1].set_xlabel('t [frames]')

    # WIDGETS
    neuron_nr_slider = IntSlider(description='Neuron Number',
                                 value=0,
                                 min=0,
                                 max=len(C) - 1)

    def neuron_nr_handler(*args):
        i = neuron_nr_slider.value
        axes[1].clear()
        axes[1].plot(C[i], label='C: raw traces', c='blue')
        axes[1].plot(Y_r[i], label='Y_r: residuals', c='red')
        axes[1].plot(S[i], label='S: deconvolved activity', c='green')
        plt.legend()
        axes[1].set_xlabel('t [frames]')

    neuron_nr_slider.observe(neuron_nr_handler, 'value')
    widgets = [neuron_nr_slider]

    return fig, widgets
Exemple #31
0
class NGLDisplay:
    """Structure display class

    Provides basic structure/trajectory display
    in the notebook and optional gui which can be used to enhance its
    usability.  It is also possible to extend the functionality of the
    particular instance of the viewer by adding further widgets
    manipulating the structure.
    """
    def __init__(self, atoms, xsize=500, ysize=500):
        import nglview
        import nglview.color

        from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox
        self.atoms = atoms
        if isinstance(atoms[0], Atoms):
            # Assume this is a trajectory or struct list
            self.view = nglview.show_asetraj(atoms, default=False)
            self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1)
            self.frm.observe(self._update_frame)
            self.struct = atoms[0]
        else:
            # Assume this is just a single structure
            self.view = nglview.show_ase(atoms, default=False)
            self.struct = atoms
            self.frm = None

        self.colors = {}
        self.view._remote_call('setSize', target='Widget',
                               args=['%dpx' % (xsize,), '%dpx' % (ysize,)])
        self.view.add_unitcell()
        self.view.add_spacefill()
        self.view.camera = 'orthographic'
        self.view.parameters = { "clipDist": 0 }

        self.view.center()

        self.asel = Dropdown(options=['All'] +
                             list(set(self.struct.get_chemical_symbols())),
                             value='All', description='Show')

        self.csel = Dropdown(options=nglview.color.COLOR_SCHEMES,
                             value='element', description='Color scheme')

        self.rad = FloatSlider(value=0.5, min=0.0, max=1.5, step=0.01,
                               description='Ball size')

        self.asel.observe(self._select_atom)
        self.csel.observe(self._update_repr)
        self.rad.observe(self._update_repr)

        self.view.update_spacefill(radiusType='covalent',
                                   radiusScale=0.5,
                                   color_scheme=self.csel.value,
                                   color_scale='rainbow')

        wdg = [self.asel, self.csel, self.rad]
        if self.frm:
            wdg.append(self.frm)

        self.gui = HBox([self.view, VBox(wdg)])
        # Make useful shortcuts for the user of the class
        self.gui.view = self.view
        self.gui.control_box = self.gui.children[1]
        self.gui.custom_colors = self.custom_colors

    def _update_repr(self, chg=None):
        self.view.update_spacefill(radiusType='covalent',
                                   radiusScale=self.rad.value,
                                   color_scheme=self.csel.value,
                                   color_scale='rainbow')

    def _update_frame(self, chg=None):
        self.view.frame = self.frm.value
        return

    def _select_atom(self, chg=None):
        sel = self.asel.value
        self.view.remove_spacefill()
        for e in set(self.struct.get_chemical_symbols()):
            if (sel == 'All' or e == sel):
                if e in self.colors:
                    self.view.add_spacefill(selection='#' + e,
                                            color=self.colors[e])
                else:
                    self.view.add_spacefill(selection='#' + e)
        self._update_repr()

    def custom_colors(self, clr=None):
        """
        Define custom colors for some atoms. Pass a dictionary of the form
        {'Fe':'red', 'Au':'yellow'} to the function.
        To reset the map to default call the method without parameters.
        """
        if clr:
            self.colors = clr
        else:
            self.colors = {}
        self._select_atom()
from ipywidgets import IntSlider, Text, VBox
from IPython.display import display

s = IntSlider(max=200, value=100)
t = Text()

def update_text(change):
    t.value = str(s.value ** 2)

s.observe(update_text, names='value')
display(VBox([s, t]))
Exemple #33
0
    def _create_controls(
        self,
        time: Union[pd.DatetimeIndex, pd.TimedeltaIndex, List[pd.Timestamp]],
        reference_system: str,
        show_data_labels: bool,
        show_labels: bool,
        show_origins: bool,
        show_traces: bool,
        show_vectors: bool,
        show_wireframe: bool,
    ):
        """Create the control panel.

        Parameters
        ----------
        time : pandas.DatetimeIndex, pandas.TimedeltaIndex, List[pandas.Timestamp], or \
               LocalCoordinateSystem
            The time steps that should be plotted initially
        reference_system : str
            Name of the initial reference system. If `None` is provided, the root system
            of the `CoordinateSystemManager` instance will be used
        show_data_labels : bool
            If `True`, the data labels will be shown initially
        show_labels  : bool
            If `True`, the coordinate system labels will be shown initially
        show_origins : bool
            If `True`, the coordinate systems' origins will be shown initially
        show_traces : bool
            If `True`, the coordinate systems' traces will be shown initially
        show_vectors : bool
            If `True`, the coordinate systems' axis vectors will be shown initially
        show_wireframe : bool
            If `True`, spatial data containing mesh data will be drawn as wireframe

        """
        num_times = 1
        disable_time_widgets = True
        lo = Layout(width="200px")

        # create widgets
        if time is not None:
            num_times = len(time)
            disable_time_widgets = False

        play = Play(
            min=0,
            max=num_times - 1,
            value=self._current_time_index,
            step=1,
        )
        time_slider = IntSlider(
            min=0,
            max=num_times - 1,
            value=self._current_time_index,
            description="Time:",
        )
        reference_dropdown = Dropdown(
            options=self._csm.coordinate_system_names,
            value=reference_system,
            description="Reference:",
            disabled=False,
        )
        data_dropdown = Dropdown(
            options=SpatialDataVisualizer.visualization_methods,
            value="auto",
            description="data repr.:",
            disabled=False,
            layout=lo,
        )

        lo = Layout(width="200px")
        vectors_cb = Checkbox(value=show_vectors,
                              description="show vectors",
                              layout=lo)
        origin_cb = Checkbox(value=show_origins,
                             description="show origins",
                             layout=lo)
        traces_cb = Checkbox(value=show_traces,
                             description="show traces",
                             layout=lo)
        labels_cb = Checkbox(value=show_labels,
                             description="show labels",
                             layout=lo)
        wf_cb = Checkbox(value=show_wireframe,
                         description="show wireframe",
                         layout=lo)
        data_labels_cb = Checkbox(value=show_data_labels,
                                  description="show data labels",
                                  layout=lo)

        jslink((play, "value"), (time_slider, "value"))
        play.disabled = disable_time_widgets
        time_slider.disabled = disable_time_widgets

        # callback functions
        def _reference_callback(change):
            self.update_reference_system(change["new"])

        def _time_callback(change):
            self.update_time_index(change["new"])

        def _vectors_callback(change):
            self.show_vectors(change["new"])

        def _origins_callback(change):
            self.show_origins(change["new"])

        def _traces_callback(change):
            self.show_traces(change["new"])

        def _labels_callback(change):
            self.show_labels(change["new"])

        def _data_callback(change):
            self.set_data_visualization_method(change["new"])

        def _data_labels_callback(change):
            self.show_data_labels(change["new"])

        def _wireframe_callback(change):
            self.show_wireframes(change["new"])

        # register callbacks
        time_slider.observe(_time_callback, names="value")
        reference_dropdown.observe(_reference_callback, names="value")
        vectors_cb.observe(_vectors_callback, names="value")
        origin_cb.observe(_origins_callback, names="value")
        traces_cb.observe(_traces_callback, names="value")
        labels_cb.observe(_labels_callback, names="value")
        data_dropdown.observe(_data_callback, names="value")
        data_labels_cb.observe(_data_labels_callback, names="value")
        wf_cb.observe(_wireframe_callback, names="value")

        # create control panel
        row_1 = HBox([time_slider, play, reference_dropdown])
        row_2 = HBox([vectors_cb, origin_cb, traces_cb, labels_cb])
        if len(self._data_vis) > 0:
            row_3 = HBox([data_dropdown, wf_cb, data_labels_cb])
            return VBox([row_1, row_2, row_3])
        return VBox([row_1, row_2])
        def _intermediate(target):
            # based on the target mask get the labels for the rest of the interactors
            target_mask = self.region_masks[target]

            def _interact_object(target_mask, pred, label, threshold=0.5):
                button, text = _create_button_text_display(
                    'object_comparison.png')

                # get the target and prediction images
                pred_mask = self.region_masks[pred]

                # calculate the iou matrix
                iou = intersection_over_union(target_mask, pred_mask)[0]

                # threshold the iou
                match = iou > threshold

                # create a copy of the raw image in rgb
                im = gray_to_rgb(normalize_image(self.region_im.copy()))

                # each row in the match array represents a target object
                match_row = match[label - 1, :]

                # get prediction labels where there is intersection
                _pred_labels = np.where(match_row)[0]

                # color codes as before - white for agreement, red for false positive, and blue for false negative
                target_mask = target_mask == label
                im[target_mask, :] = [0, 0, 255]

                # get indices where target mask is True
                row_i, col_i = np.where(target_mask)

                # color the matched predicted labels as red
                for _pred_label in _pred_labels:
                    pred_mask = pred_mask == _pred_label + 1
                    im[pred_mask, :] = [255, 0, 0]
                    im[pred_mask & target_mask, :] = [255, 255, 255]

                    # get indices where pred mask is True and append row_i, col_i
                    row_j, col_j = np.where(pred_mask)
                    row_i, col_i = np.concatenate(
                        (row_i, row_j)), np.concatenate((col_i, col_j))

                # chop the region for a closer look =)
                # pad the edges of teh chopped regionpixels on each edge but threshold
                min_y, min_x, max_y, max_x = np.min(row_i), np.min(
                    col_i), np.max(row_i), np.max(col_i)
                pad = 30
                min_y = max(0, min_y - pad)
                min_x = max(0, min_x - pad)
                max_x += pad
                max_y += pad
                chopped_im = im[min_y:max_y, min_x:max_x, :]

                print(
                    'White -> Agreement,  Blue -> False Negative,  Red -> False Positive'
                )
                print(
                    f'{len(pred_labels)} predicted object(s) overlap that pass iou threshold'
                )

                # plot the images
                fig, ax = plt.subplots(ncols=2, figsize=(15, 7))
                ax[0].imshow(im)
                ax[0].xaxis.set_visible(False)
                ax[0].yaxis.set_visible(False)
                ax[1].imshow(chopped_im)
                ax[1].xaxis.set_visible(False)
                ax[1].yaxis.set_visible(False)
                plt.show()
                button.on_click(
                    partial(self.on_button_clicked,
                            text_widget=text,
                            fig_to_save=fig))
                display(widgets.HBox([text, button]))

            _ = interact(_interact_object,
                         target_mask=fixed(target_mask),
                         pred=Dropdown(options=pred_labels,
                                       value=pred_label,
                                       description='Prediction mask:',
                                       style=DESC_STYLES),
                         label=IntSlider(
                             value=1,
                             min=1,
                             max=len(np.unique(target_mask)) - 1,
                             continuous_update=False,
                             description='Nuclei Label',
                             style={'description_width': 'initial'}),
                         threshold=FloatSlider(value=0.5,
                                               min=0.,
                                               max=1.,
                                               continuous_update=False))
Exemple #35
0
    def _default_plotter(self, mask_background=False, **kwargs):
        """
        Plot three orthogonal views.

        This is called by nifti_plotter, you shouldn't call it directly.
        """
        plt.gcf().clear()
        plt.ioff()  # disable interactive mode

        data_array = self.data.get_data()

        if not ((data_array.ndim == 3) or (data_array.ndim == 4)):
            raise ValueError('Input image should be 3D or 4D')

        # mask the background
        if mask_background:
            # TODO: add the ability to pass 'mne' to use a default brain mask
            # TODO: split this out into a different function
            if data_array.ndim == 3:
                labels, n_labels = scipy.ndimage.measurements.label(
                    (np.round(data_array) == 0))
            else:  # 4D
                labels, n_labels = scipy.ndimage.measurements.label(
                    (np.round(data_array).max(axis=3) == 0))

            mask_labels = [
                lab for lab in range(1, n_labels + 1)
                if (np.any(labels[[0, -1], :, :] == lab)
                    | np.any(labels[:, [0, -1], :] == lab)
                    | np.any(labels[:, :, [0, -1]] == lab))
            ]

            if data_array.ndim == 3:
                data_array = np.ma.masked_where(np.isin(labels, mask_labels),
                                                data_array)
            else:
                data_array = np.ma.masked_where(
                    np.broadcast_to(
                        np.isin(labels, mask_labels)[:, :, :, np.newaxis],
                        data_array.shape), data_array)

        # init sliders for the various dimensions
        for dim, label in enumerate(['x', 'y', 'z']):
            if label not in kwargs.keys():
                kwargs[label] = IntSlider(value=(data_array.shape[dim] - 1) /
                                          2,
                                          min=0,
                                          max=data_array.shape[dim] - 1,
                                          continuous_update=False)

        if (data_array.ndim == 3) or (data_array.shape[3] == 1):
            kwargs['t'] = fixed(0)  # time is fixed
        else:  # 4D
            kwargs['t'] = IntSlider(value=0,
                                    min=0,
                                    max=data_array.shape[3] - 1,
                                    continuous_update=False)

        interact(self._plot_slices, data=fixed(data_array), **kwargs)

        plt.close()  # clear plot
        plt.ion()  # return to interactive state
Exemple #36
0
    dot_data = tree.export_graphviz(
        clf,
        out_file=None,
        feature_names=X.columns,
        class_names=list(y_encoder.classes_),
        filled=True,
        rounded=True,
        special_characters=True,
    )
    graph = graphviz.Source(dot_data)
    display(SVG(graph.pipe(format='svg')))


inter = interactive(
    plot_tree,
    max_depth=IntSlider(min=1, max=15),
    min_samples_leaf=IntSlider(min=1, max=25, value=10),
)
display(inter)
# -

# # Explorando las particiones
#
# [dtreeviz](https://github.com/parrt/dtreeviz) permite explorar un poco mas los árboles. Es un poco más visual que su contraparte de sklearn. Veamos las reglas aprendidas por cada nodo.

# +
X, y, df, y_encoder = feature_engineering(dataset)
clf = get_tree(X, y)

viz = dtreeviz.dtreeviz(
    clf,
Exemple #37
0
    def _init_widget(self):
        state = self._state
        widget = dict()
        fig = dict(x=self._create_slice_fig(),
                   y=self._create_slice_fig(),
                   z=self._create_slice_fig())
        widget['fig'] = fig

        topomap_fig = dict(mag=create_topomap_fig(),
                           grad=create_topomap_fig(),
                           eeg=create_topomap_fig())
        widget['topomap_fig'] = topomap_fig

        label = dict()
        label['axis'] = dict(x=HTML(f"<b>{state['label_text']['x']}</b>"),
                             y=HTML(f"<b>{state['label_text']['y']}</b>"),
                             z=HTML(f"<b>{state['label_text']['z']}</b>"))
        label['topomap_mag'] = HTML(
            f"<b>{state['label_text']['topomap_mag']}</b>")
        label['topomap_grad'] = HTML(
            f"<b>{state['label_text']['topomap_grad']}</b>")
        label['topomap_eeg'] = HTML(
            f"<b>{state['label_text']['topomap_eeg']}</b>")

        label['dipole_pos'] = Label('Not set')
        label['dipole_ori'] = Label('Not set')
        label['dipole_pos_'] = Label('Dipole origin:')
        label['dipole_ori_'] = Label('Dipole orientation:')
        label['status'] = Label('Status:')
        label['updating'] = Label('Ready.')
        widget['label'] = label
        widget['tab'] = Tab(layout=Layout(width='700'))

        toggle_buttons = dict(
            mode_selector=ToggleButtons(options=[
                'Slice Browser', 'Set Dipole Origin', 'Set Dipole Orientation'
            ],
                                        button_style='primary',
                                        layout=Layout(width='auto')))
        toggle_buttons['mode_selector'].observe(self._handle_view_mode_change,
                                                'value')
        widget['toggle_buttons'] = toggle_buttons
        widget['reset_button'] = Button(description='Reset',
                                        button_style='danger',
                                        layout=Layout(width='auto'))
        widget['reset_button'].on_click(self._handle_reset_button_click)

        checkbox = dict(exact_solution=Checkbox(
            value=self._exact_solution,
            description='Exact solution (slow!)',
            tooltip='Calculate an exact forward projection. This is SLOW!'))
        checkbox['exact_solution'].observe(self._toggle_exact_solution,
                                           'value')
        widget['checkbox'] = checkbox

        widget['amplitude_slider'] = IntSlider(value=int(
            self._state['dipole_amplitude'] * 1e9),
                                               min=5,
                                               max=100,
                                               step=5,
                                               continuous_update=False)
        widget['amplitude_slider'].observe(self._handle_amp_change,
                                           names='value')
        widget['label']['amplitude_slider'] = Label('Dipole amplitude in nAm')

        widget['quickstart_text'] = HTML(value=(
            '<ul>'
            '<li>Select the desired brain slices in the '
            '<b>Slice Browser (or use a preset).</b></li>'
            '<li>Choose the location of the dipole via '
            '<b>Set Dipole Origin.</b></li>'
            '<li>Orient the dipole via '
            '<b>Set Dipole Orientation.</b></li>'
            '<li>Adjust the <b>dipole amplitude</b> '
            'using the slider below the topographic maps.</li>'
            '</ul>\n'
            '<p><b>This application is still '
            '<a href="https://github.com/hoechenberger/dipoles_demo/issues/26">'
            'work in progress</a>.</b></p>'))

        widget['quickstart_accordion'] = Accordion(
            children=[widget['quickstart_text']])
        widget['quickstart_accordion'].set_title(0, 'Quickstart')

        widget['preset_dropdown'] = Dropdown(
            options=['Select Preset…', 'Preset 1', 'Preset 2', 'Preset 3'],
            value='Select Preset…',
            layout=Layout(width='auto'))
        widget['preset_dropdown'].observe(self._handle_preset_selection_change,
                                          'value')

        widget['title'] = HTML(value='<h2>Dipole Simulator</h2>')

        widget['output'] = output_widget
        return widget
def view_structure(pdbIds,
                   bioAssembly=False,
                   style='cartoon',
                   color='spectrum'):
    '''A wrapper function that simply displays a list of protein structures using
    ipywidgets and py3Dmol

    Parameters
    ----------
    pdbIds : list
       A list of PDBIDs to display
    bioAssembly : bool
       display bioAssembly
    style : str, optional
       Style of 3D structure (stick line cross sphere cartoon VDW MS)
    color : str, optional
       Color of 3D structure

    '''
    if type(pdbIds) == str:
        pdbIds = [pdbIds]

    def view3d(i=0):
        '''Simple structure viewer that uses py3Dmol to view PDB structure by
        indexing the list of PDBids

        Parameters
        ----------
            i (int): index of the protein if a list of PDBids
        '''
        print(f"PdbID: {pdbIds[i]}, Style: {style}")

        if '.' not in pdbIds[i]:
            viewer = py3Dmol.view(query='pdb:' + pdbIds[i],
                                  options={'doAssembly': bioAssembly})
            viewer.setStyle({style: {'color': color}})
            viewer.setStyle({'hetflag': True},
                            {'stick': {
                                'singleBond': False
                            }})

        else:
            pdbid, chainid = pdbIds[i].split('.')
            viewer = py3Dmol.view(query='pdb:' + pdbid,
                                  options={'doAssembly': bioAssembly})
            viewer.setStyle({})
            viewer.setStyle({'chain': chainid}, {style: {'color': color}})
            viewer.setStyle({
                'chain': chainid,
                'hetflag': True
            }, {'stick': {
                'singleBond': False
            }})
            viewer.zoomTo({'chain': chainid})

        return viewer.show()

    s_widget = IntSlider(min=0,
                         max=len(pdbIds) - 1,
                         description='Structure',
                         continuous_update=False)
    return interact(view3d, i=s_widget)
class Dashboard:
    def __init__(self, df, map_file, province_id_to_name) -> None:
        self.df = df
        self.yearly_df = self.df.pipe(self.reshape_with_period_cols)
        self.years = list(self.yearly_df.columns)
        self.sc_x = LinearScale()
        self.sc_y = LinearScale()
        self.col_scale = ColorScale(scheme="Greens")
        self.geomap = self.create_map(map_file)
        self.lineplot = self.create_lineplot()
        self.province_id_to_name = province_id_to_name.copy()
        self.year_slider = IntSlider(
            description="year",
            min=1995,
            max=2001,
            continuous_update=False,
            layout=Layout(width="100%"),
        )

    def create_map(self, map_file):
        first_year = self.years[0]
        first_provincial_income_proportion = self.get_provincial_income_proportion(
            first_year)
        sc_geo = Mercator(scale_factor=7000, center=(5.5, 53.0))
        tooltip = Tooltip(fields=["name"], labels=["province"])
        return Map(
            map_data=topo_load(map_file),
            scales={
                "projection": sc_geo,
                "color": self.col_scale
            },
            colors={"default_color": "Grey"},
            color=first_provincial_income_proportion,
            tooltip=tooltip,
            interactions={
                "click": "select",
                "hover": "tooltip"
            },
            visible=True,
        )

    def create_map_figure(self):
        ax_col = ColorAxis(scale=self.col_scale,
                           label="ratio",
                           tick_format="0.2f")
        return Figure(
            marks=[self.geomap],
            axes=[ax_col],
            title="Wealth of The Netherlands",
            layout={
                "min_width": "400px",
                "width": "auto",
                "min_height": "400px",
                "width": "auto",
            },
        )

    def create_lineplot(self):
        return Lines(
            x=self.years,
            y=[],
            scales={
                "x": self.sc_x,
                "y": self.sc_y
            },
            display_legend=True,
        )

    def create_lineplot_figure(self):
        ax_x = Axis(scale=self.sc_x, label="Year", tick_values=self.years)
        ax_y = Axis(scale=self.sc_y,
                    orientation="vertical",
                    label="Thousands (Euro)")
        return Figure(
            marks=[self.lineplot],
            axes=[ax_x, ax_y],
            title="Income per Year (Click a province to show)",
            layout={
                "min_width": "400px",
                "width": "auto",
                "min_height": "400px",
                "height": "auto",
            },
        )

    def plot_yearly_income_per_province(self, *_):
        """
        on_event, when a province is clicked
        """
        if self.geomap.selected is not None and len(self.geomap.selected) > 0:
            selected_provinces = self.geomap.selected
            self.lineplot.y = self.yearly_df.loc[selected_provinces]
            self.lineplot.labels = [
                self.province_id_to_name[province_id]
                for province_id in selected_provinces
            ]
        else:
            self.lineplot.labels = []
            self.lineplot.y = []

    def update_income(self, *_):
        """
        on_event, when a year slider is changed
        """
        year = self.year_slider.value
        id_to_income = self.get_provincial_income_proportion(year)
        geomap_color_scale = self.geomap.scales["color"]
        geomap_color_scale.min = min(id_to_income.values())
        geomap_color_scale.max = max(id_to_income.values())
        self.geomap.color = id_to_income

    def reshape_with_period_cols(_, input_df):
        """
        To get a yearly dataframe, in which years are pivoted as columns
        """
        input_df = input_df.pivot(index="province_id",
                                  columns="period")[["income"]]
        # Drop higher column level, i.e income
        input_df.columns = input_df.columns.droplevel()
        return input_df

    def get_provincial_income_proportion(self, year: int) -> Dict[int, float]:
        is_within_year = self.df["period"] == year
        yearly_income = self.df[is_within_year]
        income_proportion = yearly_income["income"] / sum(
            yearly_income["income"])
        id_to_income = dict(
            zip(yearly_income["province_id"], income_proportion))
        return id_to_income

    def build(self):
        self.geomap.observe(self.plot_yearly_income_per_province, "selected")
        play_button = Play(min=1995,
                           max=2001,
                           interval=1000,
                           layout=Layout(width="100%"))
        self.year_slider.observe(self.update_income, "value")
        jslink((play_button, "value"), (self.year_slider, "value"))
        map_figure = self.create_map_figure()
        lineplot_figure = self.create_lineplot_figure()

        return VBox([
            HBox([play_button, self.year_slider]), map_figure, lineplot_figure
        ])
Exemple #40
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])
Exemple #41
-1
 def _make_resize_notebook_slider(self):
     resize_notebook_slider = IntSlider(min=300, max=2000, description='resize notebook')
     def on_resize_notebook(change):
         width = change['new']
         self._view._remote_call('resizeNotebook',
                 target='Widget',
                 args=[width,])
     resize_notebook_slider.observe(on_resize_notebook, names='value')
     return resize_notebook_slider
Exemple #42
-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
Exemple #43
-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)