Ejemplo n.º 1
1
def main(conn):
    def clear_map():
        if 'm' in globals():
            m.close()
        else:
            pass

    def clear_lat_longs():
        if 'lat_longs' in globals():
            lat_longs = None
        else:
            pass

    def clear_time_slider():
        if 'time_slider' in globals():
            time_slider = None
        else:
            pass

    def draw_update_map(b):
        clear_map()
        clear_lat_longs()
        plate = plate_dropdown.value
        start_date_time = str(
            start_date.value) + ' ' + start_time_dropdown.value
        end_date_time = str(end_date.value) + ' ' + end_time_dropdown.value
        global locations
        locations = sfmta.get_points_for_shuttle(conn, plate, start_date_time,
                                                 end_date_time)

        zip_locations = zip(locations['lng'], locations['lat'],
                            locations.index)
        global lat_longs
        lat_longs = [(x[0], x[1]) for x in zip_locations]
        index_value = find_index(lat_longs, time_slider.value)
        global m
        m = draw_map(lat_longs[:index_value])
        display(m)

    button = Button(description="Draw/Update Map")
    button.on_click(draw_update_map)
    time_slider = IntSlider(min=0,
                            max=100,
                            step=1,
                            description='% of Data',
                            value=100)

    def find_index(lat_longs, value):
        length = len(lat_longs)
        index = int(length * value / 100)
        return index

    def draw_map(lat_longs):
        center = [37.79481, -122.41186]
        zoom = 12
        m = Map(center=center, zoom=zoom, basemap=basemaps.Hydda.Full)
        m.layout.height = '650px'
        pl = Polyline(locations=lat_longs)
        pl.color = path_color.value
        pl.fill_color = path_color.value
        m.add_layer(pl)
        return m

    plates = sfmta.get_all_shuttles(conn)['LICENSE_PLATE'].unique()
    plate_dropdown = Dropdown(options=plates, description='Plate')

    def show_restrictions(b):
        polygons = './vehiclerestrictions_wgs.json'

        with open(polygons) as f:
            polygons_json = json.load(f)

        global geojson
        geojson = GeoJSON(data=polygons_json)
        m.add_layer(geojson)

    def remove_restrictions(b):
        if 'geojson' in globals():
            m.remove_layer(geojson)
        else:
            pass

    def download_data(b):
        if 'lat_longs' in globals():
            df = pd.DataFrame(data=lat_longs)
            df.to_excel('output.xlsx')
        else:
            pass

    button_restrictions = Button(description="Show Restrictions")
    button_restrictions.on_click(show_restrictions)

    button_remove_restrictions = Button(description="Hide Restrictions")
    button_remove_restrictions.on_click(remove_restrictions)

    path_color = ColorPicker(description='Color')

    export_data = Button(description="Download Data")
    export_data.on_click(download_data)

    def top_n_stops(b):
        from collections import Counter
        count_lat_longs = Counter(lat_longs).most_common()
        for lat_long in count_lat_longs[0:10]:
            location = lat_long[0]
            circle = Circle(location=location, radius=300)
            m.add_layer(circle)
        return m

    button_add_top_stops = Button(description="Display Bus Idling")
    button_add_top_stops.on_click(top_n_stops)

    # Remove map button needs its own function with a single argument
    def remove_map(b):
        clear_map()

    button_clear_map = Button(description="Remove Map")
    button_clear_map.on_click(remove_map)

    start = datetime.date.today()
    end = datetime.date.today()
    start_date = DatePicker(description='Start Date', value=start)
    end_date = DatePicker(description='End Date', value=end)

    start_time_dropdown = time_drop_down()
    start_time_dropdown.description = 'Start Time'
    end_time_dropdown = time_drop_down()
    end_time_dropdown.description = 'End Time'

    companies = sfmta.get_shuttles_companies(conn)['NAME'].unique()
    company = Dropdown(options=companies,
                       value='WeDriveU',
                       description='Company')

    return VBox([
        HBox(
            [company, button, button_restrictions,
             button_remove_restrictions]),
        HBox([
            plate_dropdown, export_data, button_add_top_stops, button_clear_map
        ]),
        HBox([path_color]),
        HBox([start_date, start_time_dropdown]),
        HBox([end_date, end_time_dropdown]),
        HBox([time_slider]),
    ])
Ejemplo n.º 2
0
 def __create_color_changer_tab(self, skeleton: DrawableSkeleton) -> \
         Tuple[VBox, Tuple[ColorPicker, ColorPicker, ColorPicker, ColorPicker]]:
     left_color_picker: ColorPicker = ColorPicker(
         description='Left color:',
         value=self.__get_as_html_color(
             skeleton.get_left_objects()[0].color))
     right_color_picker: ColorPicker = ColorPicker(
         description='Right color:',
         value=self.__get_as_html_color(
             skeleton.get_right_objects()[0].color))
     center_color_picker: ColorPicker = ColorPicker(
         description='Center color:',
         value=self.__get_as_html_color(
             skeleton.get_center_objects()[0].color))
     all_color_picker: ColorPicker = ColorPicker(description='All color:',
                                                 value='#ffffff')
     skeleton_color_updater: SkeletonColorUpdater = SkeletonColorUpdater(
         skeleton, left_color_picker, right_color_picker,
         center_color_picker)
     left_color_picker.observe(skeleton_color_updater.update_left_objects,
                               names='value')
     right_color_picker.observe(skeleton_color_updater.update_right_objects,
                                names='value')
     center_color_picker.observe(
         skeleton_color_updater.update_center_objects, names='value')
     all_color_picker.observe(skeleton_color_updater.update_all_objects,
                              names='value')
     return (VBox([
         left_color_picker, right_color_picker, center_color_picker,
         all_color_picker
     ]), (left_color_picker, right_color_picker, center_color_picker,
          all_color_picker))
Ejemplo n.º 3
0
    def interact(self):
        """
        获取交互式控制专题图样式部件
        """
        sizeslider = IntSlider(value=self.size,
                               min=0,
                               max=100,
                               step=1,
                               description='大小:',
                               disabled=False,
                               continuous_update=False,
                               orientation='horizontal',
                               readout=True,
                               readout_format='d',
                               layout=Layout(width="350px"))
        link((sizeslider, 'value'), (self, 'size'))
        global_alpha_slider = FloatSlider(value=self.global_alpha,
                                          min=0,
                                          max=1.0,
                                          step=0.1,
                                          description='透明度:',
                                          disabled=False,
                                          continuous_update=False,
                                          orientation='horizontal',
                                          readout=True,
                                          readout_format='.1f',
                                          layout=Layout(width="350px"))
        link((global_alpha_slider, 'value'), (self, 'global_alpha'))
        fill_style_color = ColorPicker(concise=False,
                                       description='填充颜色:',
                                       value=self.fill_style,
                                       disabled=False,
                                       layout=Layout(width="350px"))
        link((fill_style_color, 'value'), (self, 'fill_style'))
        shadow_color_color = ColorPicker(concise=False,
                                         description='描边颜色:',
                                         value=self.shadow_color,
                                         disabled=False,
                                         layout=Layout(width="350px"))
        link((shadow_color_color, 'value'), (self, 'shadow_color'))
        shadow_blur_slider = IntSlider(value=self.shadow_blur,
                                       min=0,
                                       max=100,
                                       step=1,
                                       description='投影模糊级数:',
                                       disabled=False,
                                       continuous_update=False,
                                       orientation='horizontal',
                                       readout=True,
                                       readout_format='d',
                                       layout=Layout(width="350px"))
        link((shadow_blur_slider, 'value'), (self, 'shadow_blur'))

        return VBox([
            sizeslider, global_alpha_slider, shadow_color_color,
            fill_style_color, shadow_blur_slider
        ])
Ejemplo n.º 4
0
    def display_rendering_settings(self):
        """Display visual controls for renderer settings"""
        def update_params(_):
            """Update renderer params"""
            self._client.set_renderer(
                accumulation=checkbox_accumulation.value,
                background_color=matplotlib.colors.to_rgb(
                    colorpicker_background.value),
                head_light=checkbox_head_light.value,
                samples_per_pixel=slider_samples_per_pixel.value,
                max_accum_frames=slider_max_accum_frames.value,
                subsampling=slider_sub_sampling.value)

        params = self._client.get_renderer()
        slider_samples_per_pixel = IntSlider(description='Samples per pixel',
                                             min=1,
                                             max=1024,
                                             value=params['samples_per_pixel'])
        slider_samples_per_pixel.observe(update_params)
        slider_max_accum_frames = IntSlider(
            description='Max accumulation frames',
            min=1,
            max=1024,
            value=params['max_accum_frames'])
        slider_max_accum_frames.observe(update_params, 'value')
        slider_sub_sampling = IntSlider(description='Sub-sampling',
                                        min=1,
                                        max=16,
                                        value=params['subsampling'])
        slider_sub_sampling.observe(update_params, 'value')
        colorpicker_background = ColorPicker(description='Background color',
                                             value=matplotlib.colors.to_hex(
                                                 params['background_color']))
        colorpicker_background.observe(update_params, 'value')
        checkbox_head_light = Checkbox(description='Head light',
                                       value=params['head_light'])
        checkbox_head_light.observe(update_params, 'value')
        checkbox_accumulation = Checkbox(description='Accumulation',
                                         value=params['accumulation'])
        checkbox_accumulation.observe(update_params, 'value')
        hbox_1 = HBox([
            slider_samples_per_pixel, slider_sub_sampling,
            slider_max_accum_frames
        ])
        hbox_2 = HBox([
            colorpicker_background, checkbox_head_light, checkbox_accumulation
        ])
        display(VBox([hbox_1, hbox_2], layout=DEFAULT_GRID_LAYOUT))
Ejemplo n.º 5
0
    def __init__(self, layer_state):

        self.state = layer_state

        self.widget_visible = Checkbox(description='visible', value=self.state.visible)
        link((self.state, 'visible'), (self.widget_visible, 'value'))

        self.widget_color = ColorPicker(description='color')
        link((self.state, 'color'), (self.widget_color, 'value'), color2hex)

        self.widget_linewidth = IntText(description='line width')
        link((self.state, 'linewidth'), (self.widget_linewidth, 'value'))

        self.widget_attribute = LinkedDropdown(self.state, 'attribute', label='attribute')

        if self.state.v_min is None:
            self.state.v_min = 0

        self.widget_v_min = FloatText(description='vmin')
        link((self.state, 'v_min'), (self.widget_v_min, 'value'))

        if self.state.v_max is None:
            self.state.v_max = 1

        self.widget_v_max = FloatText(description='vmax')
        link((self.state, 'v_max'), (self.widget_v_max, 'value'))

        self.widget_percentile = LinkedDropdown(self.state, 'percentile', label='percentile')

        super().__init__([self.widget_visible, self.widget_color,
                          self.widget_linewidth, self.widget_attribute,
                          self.widget_v_min, self.widget_v_max,
                          self.widget_percentile])
Ejemplo n.º 6
0
    def on_select_to_plot(self, change):
        """Call-back function for plotting a 3D visualisaiton of the segmentation"""

        #if the selected file has changed, import image, segmentation and global mask and plot
        if change['new'] != change['old']:
            print('new: ' + str(change['new']))
            print('old: ' + str(change['old']))

            image = skimage.io.imread(self.folder_name + '/' +
                                      self.select_file_to_plot.value,
                                      plugin='tifffile')
            image2 = skimage.io.imread(
                self.folder_name + '/' +
                os.path.splitext(self.select_file_to_plot.value)[0] +
                '_label.tif',
                plugin='tifffile')
            image3 = skimage.io.imread(
                self.folder_name + '/' +
                os.path.splitext(self.select_file_to_plot.value)[0] +
                '_region.tif',
                plugin='tifffile')

            #create ipyvolume figure
            ipv.figure()
            volume_image = ipv.volshow(image[0, :, :, :, 1],
                                       extent=[[0, 1024], [0, 1024], [-20,
                                                                      20]],
                                       level=[0.3, 0.2, 0.2],
                                       opacity=[0.2, 0, 0])
            volume_seg = ipv.plot_isosurface(np.swapaxes(image2 > 0, 0, 2),
                                             level=0.5,
                                             controls=True,
                                             color='green',
                                             extent=[[0, 1024], [0, 1024],
                                                     [-20, 20]])
            volume_reg = ipv.volshow(image3,
                                     extent=[[0, 1024], [0, 1024], [-20, 20]],
                                     level=[0.3, 0.2, 1],
                                     opacity=[0.0, 0, 0.5])
            volume_reg.brightness = 10
            volume_image.brightness = 10
            volume_image.opacity = 100
            ipv.xyzlim(0, 1024)
            ipv.zlim(-500, 500)
            ipv.style.background_color('black')

            #create additional controls to show/hide segmentation
            color = ColorPicker(description='Segmentation color')
            visible = ipw.Checkbox()
            jslink((volume_seg, 'color'), (color, 'value'))
            jslink((volume_seg, 'visible'), (visible, 'value'))
            ipv.show()
            with self.out:
                clear_output(wait=True)
                display(VBox([ipv.gcc(), color, visible]))

            viewer = napari.Viewer(ndisplay=3)
            viewer.add_image(image, colormap='red')
            viewer.add_image(image2, colormap='green', blending='additive')
            viewer.add_image(image3, colormap='blue', blending='additive')
Ejemplo n.º 7
0
    def _init_grid_widgets(self):
        self.axis_wid = ToggleButtons(
            description='Axis',
            options=['x', 'y', 'z'],
            value=self.axis
        )

        self.color_wid = ColorPicker(
            concise=True,
            description='Color',
            value=self.color
        )

        self.step_wid = FloatText(
            description='Step',
            value=self.step
        )

        self.width_wid = FloatText(
            description='Width',
            value=self.width
        )

        link((self.axis_wid, 'value'), (self, 'axis'))
        link((self.color_wid, 'value'), (self, 'color'))
        link((self.step_wid, 'value'), (self, 'step'))
        link((self.width_wid, 'value'), (self, 'width'))
Ejemplo n.º 8
0
def color_picker():
    '''
    Return a tring of color from users' manual pick
    '''
    clr = ColorPicker(concise=False,
                      description='Color:',
                      value='#5BC0DE'
                      )
    return clr
Ejemplo n.º 9
0
    def __init__(self, layer_state):

        self.state = layer_state

        self.widget_visible = Checkbox(description='visible', value=self.state.visible)
        link((self.state, 'visible'), (self.widget_visible, 'value'))

        self.widget_color = ColorPicker(description='color')
        link((self.state, 'color'), (self.widget_color, 'value'))

        super().__init__([self.widget_visible, self.widget_color])
Ejemplo n.º 10
0
 def __create_color_synchronizer_tab(
     color_pickers: List[Tuple[ColorPicker, ColorPicker, ColorPicker,
                               ColorPicker]]
 ) -> VBox:
     left_color_picker: ColorPicker = ColorPicker(description='Left color:',
                                                  value='#ffffff')
     right_color_picker: ColorPicker = ColorPicker(
         description='Right color:', value='#ffffff')
     center_color_picker: ColorPicker = ColorPicker(
         description='Center color:', value='#ffffff')
     all_color_picker: ColorPicker = ColorPicker(description='All color:',
                                                 value='#ffffff')
     color_picker_synchronizer: ColorPickerSynchronizer = ColorPickerSynchronizer(
         left_skeleton_color_pickers=[
             color_picker[0] for color_picker in color_pickers
         ],
         right_skeleton_color_pickers=[
             color_picker[1] for color_picker in color_pickers
         ],
         center_skeleton_color_pickers=[
             color_picker[2] for color_picker in color_pickers
         ],
         all_skeleton_color_pickers=[
             color_picker[3] for color_picker in color_pickers
         ],
         left_synchronizer_color_picker=left_color_picker,
         right_synchronizer_color_picker=right_color_picker,
         center_synchronizer_color_picker=center_color_picker)
     left_color_picker.observe(
         color_picker_synchronizer.sync_left_color_pickers, names='value')
     right_color_picker.observe(
         color_picker_synchronizer.sync_right_color_pickers, names='value')
     center_color_picker.observe(
         color_picker_synchronizer.sync_center_color_pickers, names='value')
     all_color_picker.observe(
         color_picker_synchronizer.sync_all_color_pickers, names='value')
     return VBox([
         left_color_picker, right_color_picker, center_color_picker,
         all_color_picker
     ])
Ejemplo n.º 11
0
    def create_category(self, name, attr, value, color, font_color):
        """Create category widget"""
        VIS = ["none", ""]
        widget = self.toggle_widgets[attr] = ToggleButton(value=value,
                                                          description=name)
        wcolor = self.color_widgets[attr] = ColorPicker(value=color,
                                                        description=name,
                                                        width="180px")
        wfont_color = self.font_color_widgets[attr] = ColorPicker(
            value=font_color, width="110px")

        def visibility(*args):
            """" Toggles visibility of category """
            self._display_stack += 1
            wcolor.layout.display = VIS[int(widget.value)]
            wfont_color.layout.display = VIS[int(widget.value)]
            self.display()

        widget.observe(visibility, "value")
        wcolor.observe(self.update_widget, "value")
        wfont_color.observe(self.update_widget, "value")
        visibility()
Ejemplo n.º 12
0
    def __init__(self, layer_state):

        self.state = layer_state

        self.widget_visible = Checkbox(description='visible', value=self.state.visible)
        link((self.state, 'visible'), (self.widget_visible, 'value'))

        self.widget_opacity = FloatSlider(min=0, max=1, step=0.01, value=self.state.alpha, description='opacity')
        link((self.state, 'alpha'), (self.widget_opacity, 'value'))

        self.widget_color = ColorPicker(description='color')
        link((self.state, 'color'), (self.widget_color, 'value'), color2hex)

        super().__init__([self.widget_visible, self.widget_opacity, self.widget_color])
Ejemplo n.º 13
0
    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()
            center_render_hbox = _make_autofit(
                HBox([
                    toggle_button_interpolate,
                    center_button,
                    render_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
Ejemplo n.º 14
0
 def clr_picker(clr, cache=False):
     if cache:
         clr_picker = ColorPicker(concise=True, value=to_hex(self.colormap[clr][0:3]), 
                 disabled=False, layout=Layout(width="30px"))
     else:
         clr_picker = ColorPicker(concise=True, value=to_hex(self.colormap[clr][0:3]), 
                 disabled=False, layout=Layout(width="25px", margin="0 0 0 8px"))
     clr_picker.observing = True
     def handle_color_picker(change):
         self.colormap[clr] = to_rgba(change.new, 1)
         self.model.plot.colormap = ListedColormap(self.colormap)
         self.model.plot.backend.plot._update_image()
     clr_picker.observe(handle_color_picker, names='value')
     self.colorpickers[clr] = clr_picker
     return clr_picker
Ejemplo n.º 15
0
    def _create_controls(self):
        """Create widget controls"""
        self.send_updates_to_renderer = False
        # Layout
        alpha_slider_item_layout = Layout(overflow_x='hidden',
                                          height='180px',
                                          max_width='20px')
        color_picker_item_layout = Layout(overflow_x='hidden',
                                          height='20px',
                                          max_width='20px')
        box_layout = Layout(display='inline-flex')

        # Sliders
        self._alpha_sliders = [
            widgets.IntSlider(continuous_update=self._continuous_update,
                              layout=alpha_slider_item_layout,
                              description=str(i),
                              orientation='vertical',
                              readout=True,
                              value=self._palette[i][3] * 256,
                              min=0,
                              max=255,
                              step=1) for i in range(len(self._palette))
        ]

        # Color pickers
        self._color_pickers = [
            ColorPicker(layout=color_picker_item_layout,
                        concise=True,
                        disabled=False) for i in range(len(self._palette))
        ]
        # Display controls
        color_box = Box(children=self._color_pickers)
        alpha_box = Box(children=self._alpha_sliders)
        box = VBox([color_box, alpha_box], layout=box_layout)

        # Attach observers
        for i in range(len(self._palette)):
            self._alpha_sliders[i].observe(self._update_colormap,
                                           names='value')
            self._color_pickers[i].observe(self._update_colorpicker,
                                           names='value')
        display(box)
        self._send_updates_to_renderer = True
Ejemplo n.º 16
0
    def __init__(self, layer_state):

        self.state = layer_state

        self.widget_visible = Checkbox(description='visible', value=self.state.visible)
        link((self.state, 'visible'), (self.widget_visible, 'value'))

        self.widget_attribute = LinkedDropdown(self.state, 'attribute', label='attribute')

        self.widget_opacity = FloatSlider(min=0, max=1, step=0.01, value=self.state.alpha, description='opacity')
        link((self.state, 'alpha'), (self.widget_opacity, 'value'))

        self.widget_contrast = FloatSlider(min=0, max=4, step=0.01, value=self.state.contrast, description='contrast')
        link((self.state, 'contrast'), (self.widget_contrast, 'value'))

        self.widget_bias = FloatSlider(min=0, max=1, step=0.01, value=self.state.bias, description='bias')
        link((self.state, 'bias'), (self.widget_bias, 'value'))

        self.widget_stretch = LinkedDropdown(self.state, 'stretch', label='stretch')

        self.widget_percentile = LinkedDropdown(self.state, 'percentile', ui_name='limits', label='percentile')

        self.widget_v_min = FloatText(description='min', value=self.state.v_min)
        link((self.state, 'v_min'), (self.widget_v_min, 'value'))

        self.widget_v_max = FloatText(description='max', value=self.state.v_max)
        link((self.state, 'v_max'), (self.widget_v_max, 'value'))

        self.widget_color = ColorPicker(description='color')
        link((self.state, 'color'), (self.widget_color, 'value'), color2hex)

        self.widget_colormap = Dropdown(options=colormaps.members, description='colormap')
        link((self.state, 'cmap'), (self.widget_colormap, 'value'))

        super().__init__()

        self.state.viewer_state.add_callback('color_mode', self.setup_widgets)

        self.setup_widgets()
 def interact(self):
     """
     获取交互式控制专题图样式部件
     """
     codomainslider = IntRangeSlider(
         value=[self.codomain[0], self.codomain[1]],
         min=self._codomainmin,
         max=self._codomainmax,
         step=1,
         description='值域范围:',
         disabled=False,
         continuous_update=False,
         orientation='horizontal',
         readout=True,
         readout_format='d',
         layout=Layout(width="350px"))
     link((codomainslider, 'value'), (self, 'codomain'))
     rslider = IntRangeSlider(value=[self.rrange[0], self.rrange[1]],
                              min=self._min_r,
                              max=self._max_r,
                              step=1,
                              description='半径范围:',
                              disabled=False,
                              continuous_update=False,
                              orientation='horizontal',
                              readout=True,
                              readout_format='d',
                              layout=Layout(width="350px"))
     link((rslider, 'value'), (self, 'rrange'))
     color = ColorPicker(concise=False,
                         description='填充颜色:',
                         value=self.color,
                         disabled=False,
                         layout=Layout(width="350px"))
     link((color, 'value'), (self, 'color'))
     return VBox([codomainslider, rslider, color])
Ejemplo n.º 18
0
        def clr_picker(enum_color, cache=False, miss_acc=False):
            '''

            '''
            def handle_color_picker(change):
                print(enum_color, change)
                self.colormap[enum_color] = to_rgba(change.new, 1)
                self.model.plot.colormap = ListedColormap(self.colormap)
                self.model.plot.backend.plot.update_image()
            

            if cache:
                clr_picker = ColorPicker(concise=True, value=to_hex(self.colormap[enum_color][0:3]), 
                        disabled=False, layout=Layout(width="30px"))
            else:
                clr_picker = ColorPicker(concise=True, value=to_hex(self.colormap[enum_color][0:3]), 
                        disabled=False, layout=Layout(width="25px", margin="0 4px 0 4px"))
            
            clr_picker.observe(handle_color_picker, names='value')
            self.colorpickers[enum_color] = clr_picker

            clr_picker.observing = True
            return clr_picker
Ejemplo n.º 19
0
    def on_select_to_plot(self, b):
        """Call-back function for plotting a 3D visualisaiton of the segmentation"""

        self.out.clear_output()

        image = skimage.io.imread(self.folders.cur_dir.as_posix() + '/' +
                                  self.folders.file_list.value[0],
                                  plugin='tifffile')
        image2 = skimage.io.imread(
            self.folders.cur_dir.as_posix() + '/' +
            os.path.splitext(self.folders.file_list.value[0])[0] +
            '_label.tif',
            plugin='tifffile')
        image3 = skimage.io.imread(
            self.folders.cur_dir.as_posix() + '/' +
            os.path.splitext(self.folders.file_list.value[0])[0] +
            '_region.tif',
            plugin='tifffile')

        scalez = 1024 / (int(self.scalingfactor.value))
        xy_extent = [0, 1024]
        #create ipyvolume figure
        with self.out:
            ipv.figure()
            self.volume_image = ipv.volshow(
                image[0, :, :, :, 1],
                extent=[xy_extent, xy_extent, [-scalez, scalez]],
                level=[0.3, 0.2, 0.2],
                opacity=[0.2, 0, 0],
                controls=False)
            self.volume_seg = ipv.plot_isosurface(
                np.swapaxes(image2 > 0, 0, 2),
                level=0.5,
                controls=False,
                color='green',
                extent=[xy_extent, xy_extent, [-scalez, scalez]])
            self.volume_reg = ipv.plot_isosurface(
                np.swapaxes(image3 > 0, 0, 2),
                level=0.5,
                controls=False,
                color='blue',
                extent=[xy_extent, xy_extent, [-scalez, scalez]])

            self.volume_reg.brightness = 10
            self.volume_image.brightness = 10
            self.volume_image.opacity = 100
            ipv.xyzlim(0, 1024)
            ipv.zlim(-500, 500)
            ipv.style.background_color('white')

            minval_data = ipw.IntSlider(min=0,
                                        max=255,
                                        value=255,
                                        description='min val')
            maxval_data = ipw.IntSlider(min=0,
                                        max=255,
                                        value=255,
                                        description='max val')
            brightness_data = ipw.FloatSlider(min=0,
                                              max=100,
                                              value=7.0,
                                              description='brightness')
            opacity_data = ipw.FloatSlider(min=0,
                                           max=100,
                                           value=7.0,
                                           description='opacity')
            level_data = ipw.FloatSlider(min=0,
                                         max=1,
                                         value=0.3,
                                         step=0.01,
                                         description='level')
            levelwidth_data = ipw.FloatSlider(min=0,
                                              max=1,
                                              value=0.1,
                                              step=0.01,
                                              description='level width')

            color = ColorPicker(description='Segmentation color')
            color2 = ColorPicker(description='Segmentation color')

            visible_seg = ipw.Checkbox()
            visible_reg = ipw.Checkbox()

            jslink((self.volume_image, 'show_min'), (minval_data, 'value'))
            jslink((self.volume_image, 'show_max'), (maxval_data, 'value'))
            jslink((self.volume_image, 'brightness'),
                   (brightness_data, 'value'))
            jslink((self.volume_image.tf, 'opacity1'), (opacity_data, 'value'))
            jslink((self.volume_image.tf, 'level1'), (level_data, 'value'))
            jslink((self.volume_image.tf, 'width1'),
                   (levelwidth_data, 'value'))
            jslink((self.volume_seg, 'color'), (color, 'value'))
            jslink((self.volume_reg, 'color'), (color2, 'value'))
            jslink((self.volume_seg, 'visible'), (visible_seg, 'value'))
            jslink((self.volume_reg, 'visible'), (visible_reg, 'value'))
            ipv.show()

            image_controls = HBox([
                VBox([minval_data, maxval_data]),
                VBox([
                    brightness_data, opacity_data, level_data, levelwidth_data
                ])
            ])
            display(
                VBox([
                    HBox([color, visible_seg]),
                    HBox([color2, visible_reg]), image_controls
                ]))
Ejemplo n.º 20
0
    def __init__(self, layer_state):

        self.state = layer_state

        self.widget_lighting = Checkbox(description='lighting',
                                        value=self.state.lighting)
        link((self.state, 'lighting'), (self.widget_lighting, 'value'))

        render_methods = 'NORMAL MAX_INTENSITY'.split()
        self.widget_render_method = Dropdown(options=render_methods,
                                             value=self.state.render_method,
                                             description='method')
        link((self.state, 'render_method'),
             (self.widget_render_method, 'value'))

        self.size_options = [32, 64, 128, 128 + 64, 256, 256 + 128, 512]
        options = [(str(k), k) for k in self.size_options]
        self.widget_max_resolution = Dropdown(options=options,
                                              value=128,
                                              description='max resolution')
        link((self.state, 'max_resolution'),
             (self.widget_max_resolution, 'value'))

        if self.state.vmin is None:
            self.state.vmin = 0

        self.widget_data_min = FloatSlider(description='min',
                                           min=0,
                                           max=1,
                                           value=self.state.vmin,
                                           step=0.001)
        link((self.state, 'vmin'), (self.widget_data_min, 'value'))
        dlink((self.state, 'data_min'), (self.widget_data_min, 'min'))
        dlink((self.state, 'data_max'), (self.widget_data_min, 'max'))

        if self.state.vmax is None:
            self.state.vmax = 1

        self.widget_data_max = FloatSlider(description='max',
                                           min=0,
                                           max=1,
                                           value=self.state.vmax,
                                           step=0.001)
        link((self.state, 'vmax'), (self.widget_data_max, 'value'))
        dlink((self.state, 'data_min'), (self.widget_data_max, 'min'))
        dlink((self.state, 'data_max'), (self.widget_data_max, 'max'))

        self.widget_clamp_min = Checkbox(description='clamp minimum',
                                         value=self.state.clamp_min)
        link((self.state, 'clamp_min'), (self.widget_clamp_min, 'value'))

        self.widget_clamp_max = Checkbox(description='clamp maximum',
                                         value=self.state.clamp_max)
        link((self.state, 'clamp_max'), (self.widget_clamp_max, 'value'))

        self.widget_color = ColorPicker(value=self.state.color,
                                        description='color')
        link((self.state, 'color'), (self.widget_color, 'value'), color2hex)

        if self.state.alpha is None:
            self.state.alpha = 1

        self.widget_opacity = FloatSlider(description='opacity',
                                          min=0,
                                          max=1,
                                          value=self.state.alpha,
                                          step=0.001)
        link((self.state, 'alpha'), (self.widget_opacity, 'value'))

        self.widget_opacity_scale = FloatLogSlider(
            description='opacity scale',
            base=10,
            min=-3,
            max=3,
            value=self.state.opacity_scale,
            step=0.01)
        link((self.state, 'opacity_scale'),
             (self.widget_opacity_scale, 'value'))

        # FIXME: this should be fixed
        # self.widget_reset_zoom = Button(description="Reset zoom")
        # self.widget_reset_zoom.on_click(self.state.viewer_state.reset_limits)

        super().__init__([
            self.widget_render_method,
            self.widget_lighting,
            self.widget_data_min,
            self.widget_data_max,
            self.widget_clamp_min,
            self.widget_clamp_max,
            self.widget_max_resolution,  # self.widget_reset_zoom,
            self.widget_color,
            self.widget_opacity,
            self.widget_opacity_scale
        ])
Ejemplo n.º 21
0
    def visualize_objects(self,
                          train_idxs=None,
                          test_idxs=None,
                          max_time_steps=None,
                          train_sim=False,
                          test_sim=True,
                          train_marker_size=4,
                          test_marker_size=6):
        """
            train_idxs - numpy array из индексов объектов (sat_id) тренировочной выборки,
                         которые надо визуализировать. Если  None - берем все объекты
                         
            test_idxs - numpy array из индексов объектов (sat_id) тренировочной выборки,
                         которые надо визуализировать. Если None - берем train_idxs
                         
            max_time_steps - максимальное количество измерений для одного объекта (sat_id)
            
            train_sim - если False - используем реальные данные (колонки без приставки sim)
            
            test_sim - если False - используем реальные (предсказанные) данные 
            (для этого в датафрейм нужно добавить приставки колонки с предсказаниями без приставки sim,
             как в трейне)
            
        """

        ipv.clear()
        if train_idxs is None:
            train_idxs = np.array(self.train_data['sat_id'].unique())
        if test_idxs is None:
            test_idxs = train_idxs

        if max_time_steps is None:
            max_time_steps_train = self.train_data.groupby(
                'sat_id').count()['epoch'].max()
            max_time_steps_test = self.test_data.groupby(
                'sat_id').count()['epoch'].max()
            max_time_steps = max(max_time_steps_train, max_time_steps_test)

        ## подготовка трейна и теста
        stream_train = self._prepare_stream('train', train_idxs,
                                            max_time_steps, train_sim)
        stream_test = self._prepare_stream('test', test_idxs, max_time_steps,
                                           test_sim)

        ## визуализация
        stream = np.dstack([stream_train[:, :, :], stream_test[:, :, :]])
        selected = stream_train.shape[2] + test_idxs
        self.q = ipv.quiver(*stream[:, :, :],
                            color="green",
                            color_selected='red',
                            size=train_marker_size,
                            size_selected=test_marker_size,
                            selected=selected)

        ##  Чтобы можно было менять размеры и цвета
        size = FloatSlider(min=1, max=15, step=0.2)
        size_selected = FloatSlider(min=1, max=15, step=0.2)
        color = ColorPicker()
        color_selected = ColorPicker()
        jslink((self.q, 'size'), (size, 'value'))
        jslink((self.q, 'size_selected'), (size_selected, 'value'))
        jslink((self.q, 'color'), (color, 'value'))
        jslink((self.q, 'color_selected'), (color_selected, 'value'))
        #         ipv.style.use('seaborn-darkgrid')
        ipv.animation_control(self.q, interval=75)
        ipv.show(
            [VBox([ipv.gcc(), size, size_selected, color, color_selected])])
Ejemplo n.º 22
0
    def __init__(self, signal_components: dict):
        """
        Summary:
            Object constructor for the base_data_displayer_widget.
            
        Arguments:
            signal_components - dictionary with the signals available for plotting.
            
        Returns :
            The newly created object
            
        Note :
            Currently, a data displayer has the following syntax
            
            {
			"signals": ["ndvi","coh_norm"],
			"bottom_bar": "b08_b11_b04",
			"bottom_bar_components": ["B08_mean","B11_mean","B04_mean"],
			"start_date": "2018-04-01",
		    "stop_date": "2018-10-31",
		    "output_folder" : "./nl/results_rest", 
		    "file_name_prefix" : "s1_s2_compo",
		    "legend" : ["NDVI","Coherence Norm"],
		    "resolution" : 72,
		    "marker_signals" : ["coh_norm"],
		    "marker_plot_type" : "tl",
        	"marker_colors" : {"drop" : "b", "peak" : "y"},
            "ylabel" : "label",
            "add_months" : true,
            }
        """

        # start creating the different widgets forming the base_data_displayer_widget
        self.signals = ["", *list(signal_components.keys())]

        self.wsm_signals = SelectMultiple(options=self.signals,
                                          value=[""],
                                          description="Signals:",
                                          placeholder="Signals",
                                          disabled=False)

        self.wdd_bottom_bar = Dropdown(options=self.signals,
                                       value="",
                                       description="Bottom Bar Signal:",
                                       placeholder="Bottom Bar Signal",
                                       disabled=False,
                                       layout={'width': 'max-content'})

        self.wdd_red = Dropdown(options=[""],
                                description="RED:",
                                placeholder="RED",
                                disabled=False,
                                layout={'width': 'max-content'})

        self.wdd_green = Dropdown(options=[""],
                                  description="GREEN:",
                                  placeholder="GREEN",
                                  disabled=False,
                                  layout={'width': 'max-content'})

        self.wdd_blue = Dropdown(options=[""],
                                 description="BLUE:",
                                 placeholder="BLUE",
                                 disabled=False,
                                 layout={'width': 'max-content'})

        def on_bottom_bar_change(change):
            components = [""]

            if self.wdd_bottom_bar.value in signal_components:
                components = signal_components[self.wdd_bottom_bar.value]

            self.wdd_red.options = components
            self.wdd_green.options = components
            self.wdd_blue.options = components

        self.wdd_bottom_bar.observe(on_bottom_bar_change, 'value')

        self.wh_bb_components = HBox(
            [self.wdd_red, self.wdd_green, self.wdd_blue])

        # start date
        wdp_start_date = DatePicker(description='Start date:', disabled=False)

        # stop date
        wdp_stop_date = DatePicker(description='Stop date:', disabled=False)

        self.whb_dates = HBox([wdp_start_date, wdp_stop_date])

        # output folder
        self.wfc_outdir = FileChooser(placeholder='Output directory',
                                      description='Output directory:',
                                      disabled=False)

        self.wfc_outdir.show_only_dirs = True

        # file name prefix
        self.wt_prefix = Text(placeholder='File name prefix',
                              description='File name prefix:',
                              disabled=False)

        self.whb_output_prop = HBox([
            VBox([HTML(value="<B>Output folder:<B>"), self.wfc_outdir]),
            self.wt_prefix
        ])

        self.wsm_markers = SelectMultiple(options=self.signals,
                                          value=[""],
                                          description="Marker signals:",
                                          placeholder="Marker signals",
                                          disabled=False,
                                          layout={'width': 'max-content'})

        # Marker plot type
        self.whb_marker_plot_type = VBox([
            HTML(value="<B>Marker plot type:</B>"),
            Checkbox(value=False,
                     description='Triangle',
                     disabled=False,
                     indent=False),
            Checkbox(
                value=False, description='Line', disabled=False, indent=False)
        ],
                                         layout=Layout(
                                             border='1px solid black',
                                             width='25%'))

        self.whb_marker_colors = VBox([
            HTML(value="<B>Marker color:</B>"),
            ColorPicker(concise=True,
                        description='Drop',
                        value="#ffffff",
                        disabled=False,
                        indent=False),
            ColorPicker(concise=True,
                        description='Peak',
                        value="#ffffff",
                        disabled=False,
                        indent=False)
        ],
                                      layout=Layout(border='1px solid black',
                                                    width='25%'))

        self.whb_markers = HBox([
            self.wsm_markers, self.whb_marker_plot_type, self.whb_marker_colors
        ],
                                layout=Layout(align_items='center',
                                              justify_content='space-around'))

        self.wit_resolution = IntText(value=72,
                                      description='Image Resolution:',
                                      disabled=False,
                                      layout=Layout(width='25%',
                                                    height='35px'))

        self.wt_ymin = FloatText(value=0,
                                 description='Y min:',
                                 disabled=False,
                                 tooltip="Minimum vertical value in plot",
                                 layout=Layout(width='25%', height='35px'))

        self.wt_ymax = FloatText(value=0,
                                 description='Y max:',
                                 disabled=False,
                                 tooltip="Maximum vertical value in plot",
                                 layout=Layout(width='25%', height='35px'))

        self.wcb_add_months = Checkbox(description='Add month names',
                                       value=True,
                                       indent=False,
                                       layout=Layout(width='25%',
                                                     height='35px'))

        self.whb_plot_prop = HBox([
            self.wit_resolution,
            Text(description='Legend',
                 disabled=False,
                 layout=Layout(width='25%', height='35px')),
            Text(description='Y label',
                 disabled=False,
                 layout=Layout(width='25%', height='35px'))
        ],
                                  layout=Layout(
                                      align_items='center',
                                      justify_content='space-around'))

        self.whb_plot_prop2 = HBox(
            [self.wt_ymin, self.wt_ymax, self.wcb_add_months],
            layout=Layout(align_items='center',
                          justify_content='space-around'))

        super().__init__([
            self.wsm_signals, self.wdd_bottom_bar, self.wh_bb_components,
            self.whb_dates, self.whb_output_prop, self.whb_markers,
            self.whb_plot_prop, self.whb_plot_prop2
        ])
Ejemplo n.º 23
0
    def __init__(self,
                 position: str = "bottomleft",
                 attr_name: str = "style",
                 kind: str = "stroke",
                 orientation: str = "horizontal",
                 transparent: bool = False,
                 a_map: Map = None,
                 layer: Layer = None,
                 place_control: bool = True):
        """Add a widget to the map that allows styling some given layer.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        wc = WidgetControl(widget=self.widget,
                           position=position,
                           transparent_bg=transparent)
        a_map.add_control(wc)
Ejemplo n.º 24
0
def ColorWidget(*args, **kw):
    """Color widget to pick hex color (defaults to black)"""
    if kw.get('value') is None:
        kw['value'] = '#000000'
    return ColorPicker(*args, **kw)
Ejemplo n.º 25
0
def draw_roaming_ui():
    global iter_slider, reset_button, color_it_button, juliabrot_button, canvases
    global drawing, uly_select, ulx_select, color_list, picker1, picker2, bump_ud_slider, hue_slider, sat_slider, val_slider
    global lry_select, lrx_select, color_it, modulo_slider, picker3, bump_lr_slider, zoom_slider, save_button

    # This establishes the size of the preview gui
    drawing = False
    color_it = True
    uly_select = 0
    ulx_select = 0
    lry_select = jgrid.settings.sizeY
    lrx_select = jgrid.settings.sizeX
    canvases = MultiCanvas(3,
                           width=jgrid.settings.sizeX * 2.5,
                           height=jgrid.settings.sizeY + 75)
    canvases[drawing_layer].font = '25px serif'
    canvases[drawing_layer].fill_style = '#aaaaaa'
    canvases[drawing_layer].line_width = 3
    canvases[interaction_layer].font = '35px serif'
    canvases[interaction_layer].fill_style = '#eee800'
    canvases[interaction_layer].stroke_style = '#ffffff'
    canvases[interaction_layer].line_width = 3
    iter_slider = FloatLogSlider(description='Iterations:',
                                 base=10,
                                 value=jgrid.settings.max_iterations,
                                 min=1,
                                 max=7,
                                 step=.01,
                                 continuous_update=False)
    iter_slider.observe(handler=iter_slider_handler, names='value')
    max_lr_bump = jgrid.settings.sizeX
    max_ud_bump = jgrid.settings.sizeY
    bump_ud_slider = IntSlider(description='Bump UD pix:',
                               value=1,
                               min=0,
                               max=max_ud_bump,
                               step=1,
                               continuous_update=False)
    bump_lr_slider = IntSlider(description='Bump LR pix:',
                               value=1,
                               min=0,
                               max=max_lr_bump,
                               step=1,
                               continuous_update=False)
    zoom_slider = FloatSlider(description='Zoom:',
                              value=2.0,
                              min=0.0,
                              max=1000.0,
                              step=.001,
                              continuous_update=False)
    #zoom_slider.observe(handler=zoom_button_handler, names='value')
    hue_slider = FloatSlider(description='Hue :',
                             value=jgrid.settings.hue,
                             min=0.0,
                             max=1.0,
                             step=.001,
                             continuous_update=False)
    sat_slider = FloatSlider(description='Sat:',
                             value=jgrid.settings.sat,
                             min=0.0,
                             max=1.0,
                             step=.01,
                             continuous_update=False)
    val_slider = FloatSlider(description='Val:',
                             value=jgrid.settings.val,
                             min=0.0,
                             max=1.0,
                             step=.02,
                             continuous_update=False)
    hue_slider.observe(handler=hue_slider_handler, names='value')
    sat_slider.observe(handler=sat_slider_handler, names='value')
    val_slider.observe(handler=val_slider_handler, names='value')
    modulo_slider = IntSlider(description='Modulo:',
                              value=jgrid.settings.modulo,
                              min=1,
                              max=1000000,
                              step=1,
                              continuous_update=False)
    modulo_slider.observe(handler=modulo_slider_handler, names='value')
    canvases[interaction_layer].on_mouse_down(on_mouse_down)
    canvases[interaction_layer].on_mouse_move(on_mouse_move)
    reset_button = Button(description='Zoom',
                          disabled=False,
                          button_style='',
                          tooltip='Click to use zoom slider setting for zoom',
                          icon='')
    reset_button.on_click(zoom_button_handler)
    save_button = Button(description='Save',
                         disabled=False,
                         button_style='',
                         tooltip='Click to save as JSON settings file',
                         icon='')
    save_button.on_click(save_button_handler)
    color_it_button = Button(description='Color/BW',
                             disabled=False,
                             button_style='',
                             tooltip='Click for BW or Color',
                             icon='')
    color_it_button.on_click(color_button_handler)
    juliabrot_button = Button(description='JM Mode',
                              disabled=False,
                              button_style='',
                              tooltip='Click for Julia or Mandelbrot',
                              icon='')
    juliabrot_button.on_click(juliabrot_button_handler)
    undo_button = Button(description='Undo',
                         disabled=False,
                         button_style='',
                         tooltip='Click to revert to last view',
                         icon='')
    undo_button.on_click(undo_button_handler)
    bleft_button = Button(description='Bump L',
                          disabled=False,
                          button_style='',
                          tooltip='Click to nudge left num bump LR pixels',
                          icon='')
    bleft_button.on_click(bleft_button_handler)
    bright_button = Button(description='Bump R',
                           disabled=False,
                           button_style='',
                           tooltip='Click to nudge right num bump LR pixels',
                           icon='')
    bright_button.on_click(bright_button_handler)
    bup_button = Button(description='Bump U',
                        disabled=False,
                        button_style='',
                        tooltip='Click to nudge up num bump UD pixels',
                        icon='')
    bup_button.on_click(bup_button_handler)
    bdown_button = Button(description='Bump D',
                          disabled=False,
                          button_style='',
                          tooltip='Click to nudge down bump UD pixels',
                          icon='')
    bdown_button.on_click(bdown_button_handler)
    picker1 = ColorPicker(description='M Color:', value=jgrid.settings.m_color)
    #picker2 = ColorPicker(description='Color 1:', value='#fff800')
    #picker3 = ColorPicker(description='Color 2:', value='#fff800')
    picker1.observe(color_picker1_handler, names='value')
    #picker2.observe(color_picker2_handler, names='value')
    #picker3.observe(color_picker3_handler, names='value')
    color_list = Dropdown(disabled=False,
                          options=[('Rainbow', 1), ('Classic', 2), ('Log', 3),
                                   ('RGB Max Iter', 4), ('Rainbow 2', 5)],
                          value=jgrid.settings.color_mode,
                          description='Color Mode:',
                          tooltip='Select built-in coloring options')
    color_list.observe(color_select_handler, names='value')
    draw_fractal(canvases, jgrid.tile_list)
    display_info(canvases, jgrid)
    return AppLayout(center=canvases,
                     header=HBox((iter_slider, bump_ud_slider, bump_lr_slider,
                                  zoom_slider)),
                     right_sidebar=VBox(
                         (picker1, color_list, hue_slider, sat_slider,
                          val_slider, modulo_slider)),
                     footer=HBox(
                         (bleft_button, bright_button, bup_button,
                          bdown_button, color_it_button, juliabrot_button,
                          reset_button, undo_button, save_button)))
Ejemplo n.º 26
0
selected = np.random.randint(0, 1000, 100)
ipv.figure()
quiver = ipv.quiver(x,
                    y,
                    z,
                    u,
                    v,
                    w,
                    size=5,
                    size_selected=8,
                    selected=selected)

from ipywidgets import FloatSlider, ColorPicker, VBox, jslink
size = FloatSlider(min=0, max=30, step=0.1)
size_selected = FloatSlider(min=0, max=30, step=0.1)
color = ColorPicker()
color_selected = ColorPicker()
jslink((quiver, 'size'), (size, 'value'))
jslink((quiver, 'size_selected'), (size_selected, 'value'))
jslink((quiver, 'color'), (color, 'value'))
jslink((quiver, 'color_selected'), (color_selected, 'value'))
VBox([ipv.gcc(), size, size_selected, color, color_selected])

#%%
# Import dependencies
import plotly
import plotly.graph_objs as go

# output_file("myfile.html")

# Configure Plotly to be rendered inline in the notebook.
Ejemplo n.º 27
0
    def _display(self):
        step_slide = IntSlider(value=self.step,
                               min=-100,
                               max=100,
                               description='step')
        delay_text = IntSlider(value=self.delay,
                               min=10,
                               max=1000,
                               description='delay')
        checkbox_interpolate = Checkbox(self.interpolate,
                                        description='interpolate')
        checkbox_spin = Checkbox(self.spin, description='spin')
        spin_x_slide = IntSlider(self._spin_x,
                                 min=-1,
                                 max=1,
                                 description='spin_x')
        spin_y_slide = IntSlider(self._spin_y,
                                 min=-1,
                                 max=1,
                                 description='spin_y')
        spin_z_slide = IntSlider(self._spin_z,
                                 min=-1,
                                 max=1,
                                 description='spin_z')
        spin_speed_slide = FloatSlider(self._spin_speed,
                                       min=0,
                                       max=0.2,
                                       step=0.001,
                                       description='spin speed')
        bg_color = ColorPicker(value='white', description='background')
        bg_color.width = 100.
        # t_interpolation = FloatSlider(value=0.5, min=0, max=1.0, step=0.1)
        interpolation_type = Dropdown(value=self._iterpolation_type,
                                      options=['linear', 'spline'])

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

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

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

        qtconsole_button = self._make_button_qtconsole()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return tab