Python bokeh.models.BoxSelectTool() Examples

The following are 4 code examples of bokeh.models.BoxSelectTool(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bokeh.models , or try the search function .
Example #1
Source File: crossbokeh.py    From certitude with GNU General Public License v2.0 5 votes vote down vote up
def create_figure():
    # args = curdoc().session_context.request.arguments
    # with open('args.txt', 'w') as the_file:
    #     the_file.write(str(curdoc().session_context.request.arguments['batchid']))
    #     the_file.write(str(args))

    df = select_units()

    xs = df[x.value].values
    ys = df[y.value].values
    df['x'] = xs
    df['y'] = ys

    source.data = df.to_dict(orient='list')

    x_title = x.value.title()
    y_title = y.value.title()

    kw = dict()
    if x.value in discrete:
        kw['x_range'] = sorted(set(xs))
    if y.value in discrete:
        kw['y_range'] = sorted(set(ys))
    # kw['title'] = "%s" % (dir(args))
    kw['title'] = "%s vs %s (%i elements)" % (x_title, y_title, len(df))

    # hover = HoverTool(tooltips=[("Address", "@HostnameIP"), ("Malware", "@Malware"), ("Compromise", "@Compromise")])
    p = figure(plot_width=500, plot_height=500, tools=[BoxSelectTool(), ResetTool()], **kw)
    p.xaxis.axis_label = x_title
    p.yaxis.axis_label = y_title

    if x.value in discrete:
        p.xaxis.major_label_orientation = pd.np.pi / 4

        # c = np.where(pandata["Compromise"] > 0, "orange", "grey")
        # sz = np.where(pandata["Compromise"] > 0, 9 * , "grey")

    p.circle(x='x', y='y', source=source, size=15,
            selection_color="orange", alpha=0.8, nonselection_alpha=0.4, selection_alpha=0.6)

    return p 
Example #2
Source File: comparison_plot.py    From estimagic with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _add_select_tools(current_src, other_src, param_plot, point_glyph):
    select_js_kwargs = {"current_src": current_src, "other_src": other_src}
    select_js_code = """
    // adapted from https://stackoverflow.com/a/44996422

    var chosen = current_src.selected.indices;
    if (typeof(chosen) == "number"){
        var chosen = [chosen]
    };

    var chosen_models = [];

    for (var i = 0; i < chosen.length; ++ i){
        chosen_models.push(current_src.data['model'][chosen[i]])
    };

    var chosen_models_indices = [];
    for (var i = 0; i < current_src.data['index'].length; ++ i){
        if (chosen_models.includes(current_src.data['model'][i])){
            chosen_models_indices.push(i)
        };
    };
    current_src.selected.indices = chosen_models_indices;
    current_src.change.emit();

    for (var i = 0; i < other_src.length; ++i){
        var chosen_models_indices = [];
        for (var j = 0; j < other_src[i].data['index'].length; ++ j){
            if (chosen_models.includes(other_src[i].data['model'][j])){
                chosen_models_indices.push(j)
            };
        };
        other_src[i].selected.indices = chosen_models_indices;
        other_src[i].change.emit();
    };

    """
    select_callback = CustomJS(args=select_js_kwargs, code=select_js_code)
    # point_glyph as only renderer assures that when a point is chosen
    # only that point's model is chosen
    # this makes it impossible to choose models based on clicking confidence bands
    tap = TapTool(renderers=[point_glyph], callback=select_callback)
    param_plot.tools.append(tap)
    boxselect = BoxSelectTool(renderers=[point_glyph], callback=select_callback)
    param_plot.tools.append(boxselect) 
Example #3
Source File: visualize_utils.py    From embedding with MIT License 4 votes vote down vote up
def visualize_self_attention_scores(tokens, scores, filename="/notebooks/embedding/self-attention.png",
                                    use_notebook=False):
    mean_prob = np.mean(scores)
    weighted_edges = []
    for idx_1, token_prob_dist_1 in enumerate(scores):
        for idx_2, el in enumerate(token_prob_dist_1):
            if idx_1 == idx_2 or el < mean_prob:
                weighted_edges.append((tokens[idx_1], tokens[idx_2], 0))
            else:
                weighted_edges.append((tokens[idx_1], tokens[idx_2], el))
    max_prob = np.max([el[2] for el in weighted_edges])
    weighted_edges = [(el[0], el[1], (el[2] - mean_prob) / (max_prob - mean_prob)) for el in weighted_edges]

    G = nx.Graph()
    G.add_nodes_from([el for el in tokens])
    G.add_weighted_edges_from(weighted_edges)

    plot = Plot(plot_width=500, plot_height=500,
                x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))
    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())

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

    graph_renderer.node_renderer.data_source.data['colors'] = Spectral8[:len(tokens)]
    graph_renderer.node_renderer.glyph = Circle(size=15, line_color=None, fill_color="colors")
    graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color="colors")
    graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color="grey")

    graph_renderer.edge_renderer.data_source.data["line_width"] = [G.get_edge_data(a, b)['weight'] * 3 for a, b in
                                                                   G.edges()]
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_width={'field': 'line_width'})
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color="grey", line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="grey", line_width=5)

    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_renderer.inspection_policy = EdgesAndLinkedNodes()

    plot.renderers.append(graph_renderer)

    x, y = zip(*graph_renderer.layout_provider.graph_layout.values())
    data = {'x': list(x), 'y': list(y), 'connectionNames': tokens}
    source = ColumnDataSource(data)
    labels = LabelSet(x='x', y='y', text='connectionNames', source=source, text_align='center')
    plot.renderers.append(labels)
    plot.add_tools(SaveTool())
    if use_notebook:
        output_notebook()
        show(plot)
    else:
        export_png(plot, filename)
        print("save @ " + filename) 
Example #4
Source File: wm_reader.py    From ditto with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def create_plot(self, updateCoordinates):
        load_x = []
        load_y = []
        load_lines_xs = []
        load_lines_ys = []
        if updateCoordinates:
            edges = [list(x) for x in self.nxGraph.edges()]

            self.plotdata = {
                'Xs': [],
                'Ys': [],
            }
            for edge in edges:
                node1, node2 = edge
                if 'x' in self.nxGraph.node[node1] and 'x' in self.nxGraph.node[node2]:
                    x1 = self.nxGraph.node[node1]['x']
                    y1 = self.nxGraph.node[node1]['y']
                    x2 = self.nxGraph.node[node2]['x']
                    y2 = self.nxGraph.node[node2]['y']
                    if None not in [x1, x2, y1, y2]:
                        self.plotdata['Xs'].append([x1, x2])
                        self.plotdata['Ys'].append([y1, y2])

                for node in [node1, node2]:
                    if 'loads' in self.nxGraph.node[node]:
                        for load_name, load_properties in self.nxGraph.node[node]['loads'].items():
                            if 'x' in self.nxGraph.node[node] and self.nxGraph.node[node]:
                                x1 = self.nxGraph.node[node]['x']
                                y1 = self.nxGraph.node[node]['y']
                                x2 = load_properties['x']
                                y2 = load_properties['y']
                                dist = np.sqrt((x1 - x2)**2 + (y1 - y2)**2)
                                if 0 not in [x1, x2, y1, y2] and dist < 500:
                                    load_x.append(x2)
                                    load_y.append(y2)
                                    load_lines_xs.append([x1, x2])
                                    load_lines_ys.append([y1, y2])

        Linesource = ColumnDataSource(self.plotdata)
        plot = figure(title=None, plot_width=900, plot_height=900,
                      tools=[ResetTool(), BoxSelectTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(),
                             PanTool()])

        # plot edges (lines, fuses, switches, transformers, regulators)
        plot.multi_line(xs="Xs", ys="Ys", source=Linesource, line_width=2, legend='Edges', line_color='#00008B') # , line_color=ColorBy
        # plot loads
        plot.triangle(x=load_x, y=load_y, legend='Loads', color='orange')
        # plot substation
        Xs, Ys = self.get_class_type_locations('substation')
        plot.circle_x(x=Xs, y=Ys, size=14, legend='Substation', fill_color='red', line_color='black')
        Xs, Ys = self.get_class_type_locations('regulator')
        plot.hex(x=Xs, y=Ys, size=14, legend='Regulators', fill_color='lightgreen', line_color='black')
        plot.multi_line(xs=load_lines_xs, ys=load_lines_ys, line_width=2, legend='Drop lines', line_color='black')

        plot.legend.location = "top_left"
        plot.legend.click_policy = "hide"
        curdoc().add_root(plot)

        show(plot)
        return