Ejemplo n.º 1
0
 def test_data_link_idempotent(self):
     table1 = Table([], 'A', 'B')
     table2 = Table([], 'C', 'D')
     link1 = DataLink(table1, table2)
     DataLink(table1, table2)
     self.assertEqual(len(Link.registry[table1]), 1)
     self.assertIn(link1, Link.registry[table1])
Ejemplo n.º 2
0
    def _link_polys(self):
        style = dict(editable=True)
        plot = dict(width=self.table_width, height=self.table_height)

        # Add annotation columns to poly data
        for col in self.poly_columns:
            if col not in self.polys:
                self.polys = self.polys.add_dimension(col, 0, '', True)
        self.poly_stream.source = self.polys
        self.vertex_stream.source = self.polys
        self._poly_selection.source = self.polys

        if len(self.polys):
            poly_data = gv.project(self.polys).split()
            self.poly_stream.event(
                data={
                    kd.name: [p.dimension_values(kd) for p in poly_data]
                    for kd in self.polys.kdims
                })

        poly_data = {
            c: self.polys.dimension_values(c, expanded=False)
            for c in self.poly_columns
        }
        if len(set(len(v) for v in poly_data.values())) != 1:
            raise ValueError('poly_columns must refer to value dimensions '
                             'which vary per path while at least one of '
                             '%s varies by vertex.' % self.poly_columns)
        self.poly_table = Table(poly_data, self.poly_columns,
                                []).opts(plot=plot, style=style)
        self.poly_link = DataLink(source=self.polys, target=self.poly_table)
        self.vertex_table = Table([], self.polys.kdims,
                                  self.vertex_columns).opts(plot=plot,
                                                            style=style)
        self.vertex_link = VertexTableLink(self.polys, self.vertex_table)
Ejemplo n.º 3
0
 def test_data_link_mismatch(self):
     polys = Polygons([np.random.rand(10, 2)])
     table = Table([('A', 1), ('B', 2)], 'A', 'B')
     DataLink(polys, table)
     layout = polys + table
     with self.assertRaises(Exception):
         bokeh_renderer.get_plot(layout)
Ejemplo n.º 4
0
    def view(self):
        layout = pn.Tabs()
        plot = None
        if self.liste_des_sources:
            plot = self.liste_des_sources.plot.graphique_default()

            plot.opts(toolbar='above',
                      default_tools=['box_select', 'wheel_zoom', 'reset'],
                      active_tools=['tap', 'wheel_zoom'])

            layout.append(
                ('Graphique', pn.Row(plot, sizing_mode='stretch_width')))

            dataTable = self.liste_des_sources._dataframe
            if hvplot.util.is_geodataframe(dataTable):
                dataTable = pd.DataFrame(dataTable.drop(['geometry'], axis=1))

            table = hv.Table(dataTable,
                             sizing_mode='stretch_width').opts(height=650,
                                                               width=1500)

            layout.append(('Table', pn.Row(table)))
            if len(plot) == len(table):
                DataLink(plot, table)
            return layout
        else:
            layout = pn.Column(pn.pane.HTML(f'Aucun catalogue disponible'),
                               sizing_mode='stretch_width')
            return layout
Ejemplo n.º 5
0
 def test_data_link_list(self):
     path = Path([[(0, 0, 0), (1, 1, 1), (2, 2, 2)]], vdims='color').options(color='color')
     table = Table([('A', 1), ('B', 2)], 'A', 'B')
     DataLink(path, table)
     layout = path + table
     plot = bokeh_renderer.get_plot(layout)
     path_plot, table_plot = (sp.subplots['main'] for sp in plot.subplots.values())
     self.assertIs(path_plot.handles['source'], table_plot.handles['source'])
Ejemplo n.º 6
0
 def test_data_link_poly_table_on_unlinked_clone(self):
     arr1 = np.random.rand(10, 2)
     arr2 = np.random.rand(10, 2)
     polys = Polygons([arr1, arr2])
     table = Table([('A', 1), ('B', 2)], 'A', 'B')
     DataLink(polys, table)
     layout = polys.clone() + table.clone(link=False)
     plot = bokeh_renderer.get_plot(layout)
     cds = list(plot.state.select({'type': ColumnDataSource}))
     self.assertEqual(len(cds), 2)
Ejemplo n.º 7
0
 def test_data_link_dynamicmap_table(self):
     dmap = DynamicMap(lambda X: Points([(0, X)]), kdims='X').redim.range(X=(-1, 1))
     table = Table([(-1,)], vdims='y')
     DataLink(dmap, table)
     layout = dmap + table
     plot = bokeh_renderer.get_plot(layout)
     cds = list(plot.state.select({'type': ColumnDataSource}))
     self.assertEqual(len(cds), 1)
     data = {'x': np.array([0]), 'y': np.array([-1])}
     for k, v in cds[0].data.items():
         self.assertEqual(v, data[k])
Ejemplo n.º 8
0
 def test_data_link_nan(self):
     arr = np.random.rand(3, 5)
     arr[0, 0] = np.nan
     data = {k: v for k, v in zip(['x', 'y', 'z'], arr)}
     a = Scatter(data, 'x', 'z')
     b = Scatter(data, 'x', 'y')
     DataLink(a, b)
     try:
         bokeh_renderer.get_plot(a + b)
     except:
         self.fail()
Ejemplo n.º 9
0
def hv_adjust_image_landmarks(image,
                              landmarks,
                              landmarks_match=None,
                              bregma_offset=None,
                              resolution=0.0194,
                              msize=40):
    '''
    TODO: merge part of this with the one for the landmarks
    landmarks are in allen reference space
    '''
    h, w = image.shape
    if bregma_offset is None:
        # then it is the center of the image
        bregma_offset = np.array([int(w / 2), int(h / 2)
                                  ])  # place bregma in the center of the image

    landmarks_im = allen_landmarks_to_image_space(landmarks.copy(),
                                                  bregma_offset, resolution)
    if landmarks_match is None:
        landmarks_match = landmarks_im
    import holoviews as hv
    from holoviews import opts, streams
    from holoviews.plotting.links import DataLink

    bounds = np.array([0, 0, w, h])
    im = hv.Image(image[::-1, :],
                  bounds=tuple(bounds.tolist())).opts(invert_yaxis=True,
                                                      cmap='gray')

    points = hv.Points(landmarks_match, vdims='color').opts(marker='+',
                                                            size=msize)
    point_stream = streams.PointDraw(data=points.columns(),
                                     add=False,
                                     num_objects=4,
                                     source=points,
                                     empty_value='black')
    table = hv.Table(points, ['x', 'y', 'name'],
                     'color').opts(title='Annotation location')
    DataLink(points, table)

    from bokeh.models import HoverTool
    hoverpts = HoverTool(tooltips=[("i", "$index")])

    widget = (im * points + table).opts(
        opts.Layout(merge_tools=False),
        opts.Points(invert_yaxis=True,
                    active_tools=['point_draw'],
                    color='color',
                    tools=[hoverpts],
                    width=int(w),
                    height=int(h)), opts.Table(editable=True))
    return widget, point_stream, landmarks_im
Ejemplo n.º 10
0
    def view(self):
        '''Return a HoloViews layout of the datashaded curve, cursors, and a table of cursor positions'''

        dshade = hd.datashade(hv.Scatter(self._timeseries)).opts(width=800)
        cursor_stream = hv.streams.PointDraw(data={
            'x': [],
            'y': []
        },
                                             empty_value=0)
        cursor_dmap = hv.DynamicMap(partial(self._snap, color='green'),
                                    streams=[cursor_stream])
        table = hv.Table(cursor_dmap, ['x', 'y']).opts(editable=True)
        DataLink(cursor_dmap, table)
        return (dshade * cursor_dmap) + table
Ejemplo n.º 11
0
 def test_data_link_poly_table(self):
     arr1 = np.random.rand(10, 2)
     arr2 = np.random.rand(10, 2)
     polys = Polygons([arr1, arr2])
     table = Table([('A', 1), ('B', 2)], 'A', 'B')
     DataLink(polys, table)
     layout = polys + table
     plot = bokeh_renderer.get_plot(layout)
     cds = list(plot.state.select({'type': ColumnDataSource}))
     self.assertEqual(len(cds), 1)
     merged_data = {'xs': [[[arr1[:, 0]]], [[arr2[:, 0]]]],
                    'ys': [[[arr1[:, 1]]], [[arr2[:, 1]]]],
                    'A': np.array(['A', 'B']), 'B': np.array([1, 2])}
     for k, v in cds[0].data.items():
         self.assertEqual(v, merged_data[k])
Ejemplo n.º 12
0
    def dataPanel(self):

        script = """
                <script>
                if (document.readyState === "complete") {
                  $('.example').DataTable();
                } else {
                  $(document).ready(function () {
                    $('.example').DataTable();
                  })
                }
                </script>
                """

        if len([
                el
                for el in self.select_column if el not in list(self.dataframe)
        ]) > 0:
            # redefinition des valeurs du widget lorsque le dataframe change mais que view n'est pas rappelé suite à un aller retour dans la pipeline
            self.settingWidgetSelectColumn()
        #html = self.dataframe[self.select_column].to_html(classes=['example', 'panel-df'])
        #layout = pn.pane.HTML(html + script, sizing_mode='stretch_width')

        for c in self.select_column:
            if isinstance(self.dataframe[c].iloc[0], list):
                self.dataframe[c] = self.dataframe[c].apply(
                    lambda x: nan if len(x) == 0 else x)

        dataTable = self.dataframe[self.select_column]

        if GeomUtil.getIsGeo(self, dataTable):
            wheel_zoom = WheelZoomTool(zoom_on_axis=False)
            tableDf = pd.DataFrame(dataTable.drop(['geometry'], axis=1))
            table = hv.Table(tableDf)

            element = GeomUtil.getGeoElementFromData(self, data=dataTable)
            map = gv.Overlay([element]).options(active_tools=['wheel_zoom'])
            DataLink(element, table)
            return (map * table).options(toolbar='above').opts(width=800,
                                                               height=600)
        else:
            return pn.Column(hv.Table(dataTable))
Ejemplo n.º 13
0
def hv_adjust_reference_landmarks(landmarks, ccf_regions, msize=40):
    '''
    landmarks = {'x': [-1.95, 0, 1.95, 0],
                 'y': [-3.45, -3.45, -3.45, 3.2],
                 'name': ['OB_left', 'OB_center', 'OB_right', 'RSP_base'],
                 'color': ['#fc9d03', '#0367fc', '#fc9d03', '#fc4103']}
    landmarks = pd.DataFrame(landmarks)
    # adjust landmarks
    wid,landmark_wid = hv_adjust_reference_landmarks(landmarks,ccf_regions)
    wid # to display
    # use the following to retrieve (on another cell) 
    landmarks = pd.DataFrame(landmark_wid.data)[['x','y','name','color']]
    '''
    import holoviews as hv
    from holoviews import opts, streams
    from holoviews.plotting.links import DataLink
    referenceplt = hv_plot_allen_regions(ccf_regions).options(
        {'Curve': {
            'color': 'black',
            'width': 600
        }})

    points = hv.Points(landmarks, vdims='color').opts(marker='+', size=msize)
    point_stream = streams.PointDraw(data=points.columns(),
                                     add=False,
                                     num_objects=4,
                                     source=points,
                                     empty_value='black')
    table = hv.Table(points, ['x', 'y', 'name'],
                     'color').opts(title='Landmarks location')
    DataLink(points, table)
    widget = (referenceplt * points + table).opts(
        opts.Layout(merge_tools=False),
        opts.Points(invert_yaxis=True,
                    active_tools=['point_draw'],
                    color='color',
                    height=500,
                    tools=['hover'],
                    width=500), opts.Table(editable=True))
    return widget, point_stream
Ejemplo n.º 14
0
def get_point_table_link(self, source, target):
    if hasattr(source.callback.inputs[0], 'crs'):
        return PointTableLink(source, target)
    else:
        return DataLink(source, target)
def plot_experiments(src,
                     experiments,
                     attr=None,
                     n_samples=10000,
                     single_mode=False,
                     width=550,
                     n_cols=3,
                     cmap=None):
    if type(experiments) == int:
        experiments = [experiments]

    if src == 'mnist' or src == 'fmnist':
        attr = 'labels'
        cmap = 'Category10'
        df = pd.read_feather(
            os.path.join(META_PATH, src, src + '_meta.feather'))
        df = df.loc[:n_samples]

    elif src == 'cartoon' or src == 'cartoon10k':
        n_file = int(np.ceil(n_samples / 10000))
        df, attr_dict = load_cartoon_meta(n_file=n_file, src=src)
        df = df.loc[:n_samples]

        if attr is None:
            print('TODO: implement DynamicMap for src=cartoon and attr=None')
            attr = 'nhair'

        if cmap is None:
            if attr == 'nhair':
                cmap = 'Category20'
            else:
                cmap = 'viridis'

    df = add_experiments(experiments, src, df)

    if n_samples > 10000:
        scatter_options = opts.Scatter(width=width,
                                       aspect=1,
                                       xaxis=None,
                                       yaxis=None,
                                       colorbar=False,
                                       cmap=cmap,
                                       nonselection_alpha=0.01,
                                       nonselection_color='black')

        return hv.Layout([
            dynspread(
                datashade(hv.Scatter(df,
                                     'x_' + str(e), ['y_' + str(e), attr],
                                     label=get_label(
                                         e, src)).opts(scatter_options),
                          aggregator=ds.count_cat(attr))) for e in experiments
        ])
    else:
        str_tooltips = "\
    	        <div> \
    	            <img src=\"@path\" width=\"100\" height=\"100\"></img> \
    	        </div> \
    	        <div> \
    	            <span style=\"font-size: 12px;\">label: @labels</span> \
    	        </div> \
    	        "

        hover = bokeh.models.HoverTool(tooltips=str_tooltips)

        scatter_options = opts.Scatter(
            width=width,
            aspect=1,
            xaxis=None,
            yaxis=None,
            colorbar=False,
            cmap=cmap,
            nonselection_alpha=0.01,
            nonselection_color='black',
            tools=[hover, 'box_select', 'lasso_select'])

        if single_mode:
            raise ValueError(
                'Implement single_mode (no layout just DynamicMap)'
            )  # TODO: single_mode

        scatter_list = [
            hv.Scatter(df,
                       'x_' + str(e), ['y_' + str(e), attr, 'path', 'labels'],
                       label=get_label(
                           e,
                           src)).opts(scatter_options).opts(color=hv.dim(attr))
            for e in experiments
        ]

        if len(scatter_list) > 2:
            [
                DataLink(scatter1, scatter2)
                for scatter1, scatter2 in combinations(scatter_list, 2)
            ]
            DataLink(scatter_list[0], scatter_list[1])

        return hv.Layout(scatter_list).cols(n_cols).relabel(src +
                                                            ' plotting ' +
                                                            str(n_samples) +
                                                            ' datapoints')