Ejemplo n.º 1
0
    def windBarb(self, figure):
        self.source_barb = ColumnDataSource(data.EMPTY)
        render_barb = figure.barb(x="xs",
                                  y="ys",
                                  u=-50,
                                  v=-50,
                                  source=self.source_barb)

        tool4 = PointDrawTool(renderers=[render_barb],
                              custom_icon='forest/wind/barb.png')
        return tool4
Ejemplo n.º 2
0
    def windBarb(self):
        '''
            Draws a windbarb based on u and v values in ms¯¹. Currently fixed to 50ms¯¹.

        '''
        render_lines = []
        for figure in self.figures:
            render_lines.append(
                figure.barb(x="xs",
                            y="ys",
                            u=-50,
                            v=-50,
                            source=self.source['barb']))

        tool4 = PointDrawTool(renderers=render_lines,
                              tags=['barcwindbarb'],
                              custom_icon=wind.__file__.replace(
                                  '__init__.py', 'barb.png'))

        return tool4
Ejemplo n.º 3
0
def render_from_fb_combined():
    print('rendering from facebook_combined.txt')
    df = pd.read_csv('facebook_combined.txt', sep=" ", header=None)
    G = nx.from_pandas_edgelist(df.head(1000), 0, 1)
    print(nx.info(G))

    plot = Plot(background_fill_color="white",
                sizing_mode="stretch_both",
                x_range=Range1d(-0.5, 0.5), y_range=Range1d(-0.5, 0.5))

    graph_renderer = from_networkx(
        G, nx.spring_layout, scale=1, center=(0, 0))

    graph_renderer.node_renderer.glyph = Circle(
        size=15, fill_color=Spectral4[0])
    graph_renderer.edge_renderer.glyph = MultiLine(
        line_alpha=0.8, line_width=1)

    plot.add_tools(WheelZoomTool())
    plot.add_tools(ResetTool())
    plot.add_tools(PanTool())
    plot.add_tools(HoverTool(
        tooltips=[("user", "datracka"), ("url", "https://twitter.com/datracka")]))
    plot.add_tools(PointDrawTool(
        renderers=[], empty_value='black'))

    plot.axis.axis_line_width = 0
    plot.grid.grid_line_width = 0
    plot.xaxis.major_tick_line_color = None  # turn off x-axis major ticks
    plot.xaxis.minor_tick_line_color = None  # turn off x-axis minor ticks
    plot.yaxis.major_tick_line_color = None  # turn off y-axis major ticks
    plot.yaxis.minor_tick_line_color = None  # turn off y-axis minor ticks
    plot.xaxis.major_label_text_color = None  # Remove label x axis
    plot.yaxis.major_label_text_color = None  # Remove label x axis
    plot.border_fill_color = None
    plot.outline_line_color = None

    plot.renderers.append(graph_renderer)

    return plot
Ejemplo n.º 4
0
                   line_color="lcol",
                   line_width=3)
    txt = Text(x='tsneX',
               y='tsneY',
               text='title',
               text_alpha='txt_alpha',
               text_align='center')
    p1.add_glyph(filsource, txt)

    hover = HoverTool()
    hover.tooltips = [('Votes', '@n_vote'), ('Adoption', '@vote'),
                      ('Titre', '@title')]
    hover.renderers = [r1]

    p1.add_tools(hover)
    tool = PointDrawTool(renderers=[r1], num_objects=2000)
    p1.add_tools(tool)

    filsource.selected.js_on_change(
        'indices',
        CustomJS(args=dict(source=filsource, s2=s2, div=div),
                 code="""
            var inds = cb_obj.indices;
            var d1 = source.data;
            var d2 = s2.data;
            d2['vote'] = []
            d2['n_vote'] = []
            d2['title'] = []
            d2['body'] = []
            d2['id'] = []
            var totvot=0;
Ejemplo n.º 5
0
def make_explorer(data_file, explorer_type='Customised'):
    #explorer_type options: 'Customised', 'Small', 'Big'

    def go_back():
        som.revert_active_learning()
        groove_map_info.update(
            pd.DataFrame(
                get_winners(features, names, som, palette_names),
                columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour']))
        for i in range(94):
            new_X = groove_map_info['X'][i]
            new_Y = groove_map_info['Y'][i]
            source.patch({'X': [(i, new_X)], 'Y': [(i, new_Y)]})

    def reset():
        som.reset_active_learning()
        groove_map_info.update(
            pd.DataFrame(
                get_winners(features, names, som, palette_names),
                columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour']))
        for i in range(94):
            new_X = groove_map_info['X'][i]
            new_Y = groove_map_info['Y'][i]
            source.patch({'X': [(i, new_X)], 'Y': [(i, new_Y)]})

    def pan_python_callback():
        print('pan callback executed')
        for i in range(94):
            if source.data['X'][i] != groove_map_info['X'][i]:
                old_coordinates = [
                    int(round(groove_map_info['X'][i], 0)),
                    int(round(groove_map_info['Y'][i], 0))
                ]

                new_X = round(source.data['X'][i], 0) + round(
                    random.uniform(-0.2, 0.2), 2)
                new_Y = round(source.data['Y'][i], 0) + round(
                    random.uniform(-0.2, 0.2), 2)
                # source.patch({'X': [(i, new_X)], 'Y': [(i, new_Y)]})
                groove_map_info.at[i, 'X'] = new_X
                groove_map_info.at[i, 'Y'] = new_Y

                new_coordinates = [int(round(new_X, 0)), int(round(new_Y, 0))]
                print("Groove = ", source.data['GrooveName'][i])
                print("New coordinates = ", new_coordinates)
                print("Old coordinates =", old_coordinates)

                groove = features[i]
                som.update_active_learning_nurnberger_local(
                    groove, new_coordinates, old_coordinates)
        groove_map_info.update(
            pd.DataFrame(
                get_winners(features, names, som, palette_names),
                columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour']))
        for i in range(94):
            new_X = groove_map_info['X'][i]
            new_Y = groove_map_info['Y'][i]
            source.patch({'X': [(i, new_X)], 'Y': [(i, new_Y)]})
        print('Done')

    def make_audio_panel(explorer_type):
        PLAY_TEST_AUDIO = """
        var index = selector.active;
        var labels = ['A', 'B', 'C', 'D', 'E'];
        var filename = path + labels[index] + '.mp3';
        audio_player.stop_audio();
        audio_player.play_audio(filename);
        """

        STOPCODE = """
        audio_player.stop_audio();
        """

        if explorer_type == 'Small':
            test_audio_path = 'Groove-Explorer-2/static/Test Audio/Groove Explorer Part 1 - Small/'
        if explorer_type == 'Customised':
            test_audio_path = 'Groove-Explorer-2/static/Test Audio/Groove Explorer Part 2 - Customisable/'

        labels = ['A', 'B', 'C', 'D', 'E']
        audio_selector = RadioGroup(labels=labels,
                                    height_policy="auto",
                                    sizing_mode='scale_width',
                                    active=0)

        play_button = Button(label='Play')
        play_button.js_on_click(
            CustomJS(args=dict(selector=audio_selector, path=test_audio_path),
                     code=PLAY_TEST_AUDIO))
        stop_button = Button(label='Stop')
        stop_button.js_on_click(CustomJS(code=STOPCODE))
        audio_panel = column(audio_selector, play_button, stop_button)
        return audio_panel

    PLAY_FROM_EXPLORER = """
    var selected = source.selected.indices;
    var groovename = source.data['GrooveName'][selected[0]];
    var palette = source.data['PaletteName'][selected[0]];
    var filetype = ".mp3";
    var filename = path + palette + '/' + groovename + '.mp3'
    audio_player.stop_audio();
    audio_player.play_audio(filename);
    """

    hover = HoverTool()
    hover.tooltips = [
        ('Name', '@GrooveName'),
        ('Palette', '@PaletteName'),
    ]
    TOOLS = "crosshair, wheel_zoom, pan, reset"

    if explorer_type in ['Small', 'Customised']:
        dim = 12
        som, features, names, palette_names = setup_SOM(data_file, dim)
        if explorer_type == 'Small':
            explorer_audio_path = "Groove-Explorer-2/static/Part 1 MP3 - Seperate Folders/"
            som.weights = np.load(
                "Groove-Explorer-2/SOM_Weights_MLR_3M_Part1.npy")
        elif explorer_type == 'Customised':
            explorer_audio_path = "Groove-Explorer-2/static/Part 3 MP3 - Seperate Folders/"
            som.weights = np.load(
                "Groove-Explorer-2/SOM_Weights_MLR_2M_Part3.npy")
        groove_map_info = pd.DataFrame(
            get_winners(features, names, som, palette_names),
            columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour'])
        source = ColumnDataSource(groove_map_info)
        explorer = figure(x_range=(-1, dim),
                          y_range=(-1, dim),
                          tools=TOOLS,
                          title='Groove Explorer 2')
        audio_selector = make_audio_panel(explorer_type)

    elif explorer_type == 'Big':
        dim = 28
        som, features, names, palette_names = setup_SOM(data_file, dim)
        explorer_audio_path = "Groove-Explorer-2/static/Big_Dataset_Reduced/"
        som.weights = np.load(
            "Groove-Explorer-2/SOM_Weights_MLR_3M_BIG_s3-5_28x28.npy")
        groove_map_info = pd.DataFrame(
            get_winners(features, names, som, palette_names),
            columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour'])
        source = ColumnDataSource(groove_map_info)
        explorer = figure(x_range=(-1, dim),
                          y_range=(-1, dim),
                          tools=TOOLS,
                          title='Groove Explorer 2',
                          plot_width=700,
                          plot_height=700)

    explorer.add_tools(hover)
    explorer.add_tools(
        TapTool(callback=CustomJS(code=PLAY_FROM_EXPLORER,
                                  args=dict(source=source,
                                            path=explorer_audio_path))))

    renderer = explorer.circle(source=source,
                               x='X',
                               y='Y',
                               color='Colour',
                               fill_alpha=0.6,
                               size=15,
                               hover_fill_color='yellow',
                               hover_alpha=1,
                               nonselection_alpha=0.6)

    if explorer_type == 'Customised':
        point_drag = PointDrawTool(renderers=[renderer], add=False)
        explorer.add_tools(point_drag)
        explorer.on_event(PanEnd, pan_python_callback)
        go_back_button = Button(label='Undo Customize')
        reset_button = Button(label='Reset Customization')
        go_back_button.on_click(go_back)
        reset_button.on_click(reset)
        return row(column(explorer, go_back_button, reset_button),
                   audio_selector)

    elif explorer_type == 'Small':
        return row(explorer, audio_selector)
    elif explorer_type == 'Big':
        return explorer
Ejemplo n.º 6
0
    def textStamp(self, figure):
        self.source_text_stamp = ColumnDataSource(data.EMPTY)
        self.source_text_stamp.add([], "datasize")
        self.source_text_stamp.add([], "fontsize")
        self.source_text_stamp.add([], "colour")
        #render_text_stamp = self.figure.circle(x="xs",y="ys",legend_label="X", source=source);
        starting_font_size = 30  #in pixels
        starting_colour = "orange"  #in CSS-type spec
        '''glyph = bokeh.models.Text(
                x="xs", 
                y="ys", 
                text=value("🌧"),  
                text_color="colour",
                text_font_size="fontsize")'''
        #glyph.text_font_size = '%spx' % starting_font_size

        #render_text_stamp = self.figure.add_glyph(self.source_text_stamp, glyph)
        render_text_stamp = figure.text_stamp(x="xs",
                                              y="ys",
                                              source=self.source_text_stamp,
                                              text=value("🌧"),
                                              text_color="colour",
                                              text_font_size="fontsize")

        self.source_text_stamp.js_on_change(
            'data',
            bokeh.models.CustomJS(args=dict(
                datasource=render_text_stamp.data_source,
                starting_font_size=starting_font_size,
                figure=figure,
                starting_colour=starting_colour),
                                  code="""
                for(var g = 0; g < datasource.data['fontsize'].length; g++)
                {
                    if(!datasource.data['colour'][g])
                    {
                        datasource.data['colour'][g] = starting_colour;
                    }

                    if(!datasource.data['fontsize'][g])
                    {
                        datasource.data['fontsize'][g] = starting_font_size +'px';
                    }

                    //calculate initial datasize
                    if(!datasource.data['datasize'][g])
                    {
                        var starting_font_proportion = starting_font_size/(figure.inner_height);
                        datasource.data['datasize'][g] = (starting_font_proportion * (figure.y_range.end - figure.y_range.start));
                    }
                }
                """))
        figure.y_range.js_on_change(
            'start',
            bokeh.models.CustomJS(args=dict(
                render_text_stamp=render_text_stamp,
                glyph=render_text_stamp.glyph,
                figure=figure,
                starting_font_size=starting_font_size),
                                  code="""

            for(var g = 0; g < render_text_stamp.data_source.data['fontsize'].length; g++)
            {
                 render_text_stamp.data_source.data['fontsize'][g] = (((render_text_stamp.data_source.data['datasize'][g])/ (figure.y_range.end - figure.y_range.start))*figure.inner_height) + 'px';
            }
            glyph.change.emit();
            """))
        #render_text_stamp = bokeh.models.renderers.GlyphRenderer(data_source=ColumnDataSource(dict(x=x, y=y, text="X")), glyph=bokeh.models.Text(x="xs", y="ys", text="text", angle=0.3, text_color="fuchsia"))
        tool3 = PointDrawTool(renderers=[render_text_stamp], )
        return tool3
Ejemplo n.º 7
0
    def textStamp(self, glyph=chr(0x0f0000)):
        '''Creates a tool that allows arbitrary Unicode text to be "stamped" on the map. Echos to all figures.

        :param glyph: Arbitrary unicode string, usually (but not required to be) a single character.

        returns:
            PointDrawTool with textStamp functionality.
        '''

        starting_font_size = 15  # in pixels
        render_lines = []
        for figure in self.figures:
            render_lines.append(
                figure.text_stamp(x="xs",
                                  y="ys",
                                  source=self.source['text_stamp' + glyph],
                                  text=value(glyph),
                                  text_font='BARC',
                                  text_color="colour",
                                  text_font_size="fontsize"))

        self.source['text_stamp' + glyph].js_on_change(
            'data',
            bokeh.models.CustomJS(args=dict(
                datasource=self.source['text_stamp' + glyph],
                starting_font_size=starting_font_size,
                figure=self.figures[0],
                colourPicker=self.colourPicker,
                widthPicker=self.widthPicker,
                saveArea=self.saveArea),
                                  code="""
                for(var g = 0; g < datasource.data['xs'].length; g++)
                {
                    if(!datasource.data['colour'][g])
                    {
                        datasource.data['colour'][g] = colourPicker.color;
                    }

                    if(!datasource.data['fontsize'][g])
                    {
                        datasource.data['fontsize'][g] = (widthPicker.value * starting_font_size) +'px';
                    }

                    //calculate initial datasize
                    if(!datasource.data['datasize'][g])
                    {
                        var starting_font_proportion = (widthPicker.value * starting_font_size)/(figure.inner_height);
                        datasource.data['datasize'][g] = (starting_font_proportion * (figure.y_range.end - figure.y_range.start));
                    }
                }
                """))
        self.figures[0].y_range.js_on_change(
            'start',
            bokeh.models.CustomJS(args=dict(render_text_stamp=render_lines[0],
                                            figure=self.figures[0]),
                                  code="""
            for(var g = 0; g < render_text_stamp.data_source.data['fontsize'].length; g++)
            {
                 render_text_stamp.data_source.data['fontsize'][g] = (((render_text_stamp.data_source.data['datasize'][g])/ (figure.y_range.end - figure.y_range.start))*figure.inner_height) + 'px';
            }
            render_text_stamp.glyph.change.emit();
            """))
        tool3 = PointDrawTool(
            renderers=[render_lines[0]],
            tags=['barc' + glyph],
        )
        return tool3