Exemplo n.º 1
0
    def build_graph_renderer(graph, nodes, node_colors, node_sizes, node_scores, node_labels, levels):
        graph_renderer = from_networkx(graph, nx.kamada_kawai_layout)

        level_1 = list()
        for node in nodes:
            if node in levels[1]:
                level_1.append(1)
            else:
                level_1.append(0)

        graph_renderer.node_renderer.data_source.data['index'] = nodes
        graph_renderer.node_renderer.data_source.data['color'] = node_colors
        graph_renderer.node_renderer.data_source.data['size'] = node_sizes
        graph_renderer.node_renderer.data_source.data['root_score'] = node_scores[0]
        graph_renderer.node_renderer.data_source.data['usage_score'] = node_scores[1]
        graph_renderer.node_renderer.data_source.data['label'] = node_labels
        graph_renderer.node_renderer.data_source.data['level_1'] = level_1

        graph_renderer.node_renderer.glyph = Circle(size="size", fill_color="color")
        graph_renderer.node_renderer.selection_glyph = Circle(size="size", fill_color="color")
        graph_renderer.node_renderer.hover_glyph = Circle(size="size", fill_color="color")

        graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
        graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
        graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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

        return graph_renderer
Exemplo n.º 2
0
def NLD_pocessing_graph(g, weights, colors, layout):
    graph = from_networkx(g, layout, scale=1, center=(0, 0))

    # nodes and egdes attributes
    graph.node_renderer.data_source.data['degree'] = list(zip(*g.degree))[1]
    graph.edge_renderer.data_source.data['weight'] = weights
    graph.edge_renderer.data_source.add(colors, 'color')

    graph.node_renderer.glyph = Circle(size='nodesize',
                                       fill_alpha=0.8,
                                       fill_color='royalblue')
    graph.node_renderer.selection_glyph = Circle(size=10,
                                                 fill_alpha=0.8,
                                                 fill_color='red')
    graph.node_renderer.hover_glyph = Circle(size=10,
                                             fill_alpha=0.8,
                                             fill_color='yellow')

    graph.edge_renderer.glyph = MultiLine(line_width=2.5,
                                          line_alpha=0.8,
                                          line_color='color')
    graph.edge_renderer.selection_glyph = MultiLine(line_width=2.5,
                                                    line_alpha=0.8,
                                                    line_color='red')
    graph.edge_renderer.hover_glyph = MultiLine(line_width=2.5,
                                                line_alpha=0.8,
                                                line_color='yellow')
    graph.edge_renderer.glyph.line_width = {'field': 'weight'}

    graph.selection_policy = NodesAndLinkedEdges()
    graph.inspection_policy = NodesAndLinkedEdges()

    return graph
Exemplo n.º 3
0
def circuit_from(bqm):
    G = bqm.to_networkx_graph()
    plot = Plot(
        plot_width=600, plot_height=400, x_range=Range1d(-0.1, 1.1), y_range=Range1d(-0.1, 1.1)
    )
    plot.title.text = "Multiplication as a BQM"
    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
    graph_renderer = from_networkx(G, circuit_layout)

    circle_size = 25
    graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="#F5F7FB")
    graph_renderer.node_renderer.selection_glyph = Circle(size=circle_size, fill_color="#EEA64E")
    graph_renderer.node_renderer.hover_glyph = Circle(size=circle_size, fill_color="#FFE86C")

    edge_size = 2
    graph_renderer.edge_renderer.glyph = MultiLine(
        line_color="#CCCCCC", line_alpha=0.8, line_width=edge_size
    )
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color="#EEA64E", line_width=edge_size
    )
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="#FFE86C", line_width=edge_size)

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

    plot.renderers.append(graph_renderer)

    plot.background_fill_color = "#202239"

    add_labels(plot)
    show(Row(plot))
Exemplo n.º 4
0
def NLD_FD_pocessing_graph(g, weights, colors):
    degree_sequence = sorted([d for n, d in g.degree()], reverse=True)

    magicnumber = (g.number_of_nodes() / degree_sequence[0]**2)
    r = 2.2 / magicnumber
    my_points = nx.fruchterman_reingold_layout(g, k=r, iterations=100)

    graph_fd = from_networkx(g, my_points)

    #posxy=nx.fruchterman_reingold_layout(g)
    #for i in range(len(posxy()):
    #    posxy
    #radii = np.random.random(size=N) * 1.5
    my_colors = []
    for key, value in my_points.items():
        x = value[0] + 1.0  # x = -1 .. +1, so move to 0 ... 2
        y = value[1] + 1.0  # y = -1 .. +1, so move to 0 ... 2
        my_colors.append("#%02x%02x%02x" %
                         (int(50 + 100 * x), int(30 + 100 * y), 150))

    # nodes and egdes attributes
    graph_fd.node_renderer.data_source.data['degree'] = list(zip(*g.degree))[1]
    graph_fd.node_renderer.data_source.data['degree2'] = [
        sqrt(x + 6) for x in graph_fd.node_renderer.data_source.data['degree']
    ]
    graph_fd.node_renderer.data_source.data['nodessize'] = [
        x * 115 / (sqrt(g.number_of_nodes() + (np.mean(degree_sequence))))
        for x in graph_fd.node_renderer.data_source.data['degree2']
    ]

    graph_fd.node_renderer.data_source.data['my_fill_color'] = my_colors
    graph_fd.edge_renderer.data_source.data['weight'] = weights
    graph_fd.edge_renderer.data_source.add(colors, 'color')

    graph_fd.node_renderer.glyph = Circle(size="nodesize",
                                          fill_color='my_fill_color',
                                          fill_alpha=0.85)
    graph_fd.node_renderer.selection_glyph = Circle(size=15,
                                                    fill_alpha=0.8,
                                                    fill_color='red')
    graph_fd.node_renderer.hover_glyph = Circle(size=15,
                                                fill_alpha=0.8,
                                                fill_color='yellow')

    graph_fd.edge_renderer.glyph = MultiLine(line_width=2.5,
                                             line_alpha=0.8,
                                             line_color='color')
    graph_fd.edge_renderer.selection_glyph = MultiLine(line_width=2.5,
                                                       line_alpha=0.8,
                                                       line_color='red')
    graph_fd.edge_renderer.hover_glyph = MultiLine(line_width=2.5,
                                                   line_alpha=0.8,
                                                   line_color='yellow')
    graph_fd.edge_renderer.glyph.line_width = {'field': 'weight'}

    graph_fd.selection_policy = NodesAndLinkedEdges()
    graph_fd.inspection_policy = NodesAndLinkedEdges()

    return graph_fd
Exemplo n.º 5
0
def graphNetwork(adjm, data):
    G = nx.from_numpy_matrix(adjm)
    data['degree'] = list(dict(G.degree).values())
    subgraphs = getSubgraphs(G)
    subgraphs = data.join(subgraphs.set_index('nodes'))
    subgraphs['subsets'] = adjm.sum(axis=0)

    graph_plot = Plot(plot_width=800,
                      plot_height=800,
                      x_range=Range1d(-1.1, 1.1),
                      y_range=Range1d(-1.1, 1.1))

    graph_plot.title.text = "Graph.\nTotal Nodes: %i\nTotal Edges: %i\t Total subgraphs:%i" % (
        G.number_of_nodes(), G.number_of_edges(),
        len(subgraphs.subgraph.unique()))

    node_hover_tool = HoverTool(
        tooltips=[("hashtag",
                   "@hashtag"), ("freq", "@frequency"), (
                       'degree',
                       '@degree'), ('subsets',
                                    '@subsets'), ('subgraph',
                                                  '@subgraph'), ('ix', '@ix')])
    graph_plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(),
                         WheelZoomTool())

    graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))
    graph_renderer.node_renderer.glyph = Circle(size=18, fill_color='#277bb6')
    graph_renderer.node_renderer.hover_glyph = Circle(size=18,
                                                      fill_color='#E84A5F')
    graph_renderer.node_renderer.glyph.properties_with_values()
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="gray",
                                                   line_alpha=0.7,
                                                   line_width=0.3)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color='#e09e8f',
                                                         line_width=3)
    graph_renderer.node_renderer.data_source.data[
        'hashtag'] = subgraphs.ht.values
    graph_renderer.node_renderer.data_source.data[
        'frequency'] = subgraphs.frq.values
    graph_renderer.node_renderer.data_source.data[
        'degree'] = subgraphs.degree.values
    graph_renderer.node_renderer.data_source.data[
        'subgraph'] = subgraphs.subgraph.values
    graph_renderer.node_renderer.data_source.data['ix'] = list(subgraphs.index)
    graph_renderer.node_renderer.data_source.data[
        'subsets'] = subgraphs.subsets.values

    graph_renderer.inspection_policy = NodesAndLinkedEdges()
    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_plot.toolbar.active_inspect = [node_hover_tool]
    graph_plot.renderers.append(graph_renderer)

    #output_file(path+topic+"_graph_N"+str(nodeThresh)+'E'+str(edgeThresh)+".html")

    show(graph_plot)

    subgraphs = subgraphs.sort_values(by='subgraph')
    return subgraphs
Exemplo n.º 6
0
def make_plottable(colors=None, sizes=None, tweets=None):
    global NETWORK
    if not NETWORK:
        NETWORK = reload_json(USER_GRAPH_FNAME,
                              nx.DiGraph,
                              transform=nx.node_link_graph)
    graph = from_networkx(NETWORK, graphviz_layout, prog="sfdp")

    if not colors:
        node_color = Spectral4[0]
    else:
        node_color = "color"
        graph.node_renderer.data_source.add(colors, "color")

    if not sizes:
        node_size = 8
    else:
        node_size = "size"
        graph.node_renderer.data_source.add(sizes, "size")

    if tweets:
        graph.node_renderer.data_source.add(tweets, "desc")

    edge_width = 0.3
    select_edge_width = 2
    node_alpha = 0.95
    edge_alpha = 0.3
    edge_color = "#666666"
    select_color = Spectral4[2]
    hover_color = Spectral4[1]

    graph.node_renderer.glyph = Circle(
        size=node_size,
        fill_color=node_color,
        fill_alpha=node_alpha,
        line_color=node_color,
        line_alpha=node_alpha,
    )
    graph.node_renderer.selection_glyph = Circle(size=node_size,
                                                 fill_color=select_color,
                                                 line_color=select_color)
    graph.node_renderer.hover_glyph = Circle(size=node_size,
                                             fill_color=hover_color,
                                             line_color=hover_color)

    graph.edge_renderer.glyph = MultiLine(line_color=edge_color,
                                          line_alpha=edge_alpha,
                                          line_width=edge_width)
    graph.edge_renderer.selection_glyph = MultiLine(
        line_color=select_color, line_width=select_edge_width)
    graph.edge_renderer.hover_glyph = MultiLine(line_color=hover_color,
                                                line_width=select_edge_width)
    graph.selection_policy = NodesAndLinkedEdges()
    graph.inspection_policy = NodesAndLinkedEdges()

    return graph
Exemplo n.º 7
0
def NLD_random_processing_graph(g, weights, colors, layout):
    degree_sequence = sorted([d for n, d in g.degree()], reverse=True)

    magicnumber = (g.number_of_nodes() / degree_sequence[0]**2)
    r = 2.2 / magicnumber
    my_points = nx.random_layout(g)

    graph = from_networkx(g, layout)

    my_colors = []
    for key, value in my_points.items():
        x = value[0] + 1.0  # x = -1 .. +1, so move to 0 ... 2
        y = value[1] + 1.0  # y = -1 .. +1, so move to 0 ... 2
        my_colors.append("#%02x%02x%02x" %
                         (int(50 + 100 * x), int(30 + 100 * y), 150))

    # nodes and egdes attributes
    graph.node_renderer.data_source.data['degree'] = list(zip(*g.degree))[1]
    graph.node_renderer.data_source.data['degree2'] = [
        sqrt(x + 6) for x in graph.node_renderer.data_source.data['degree']
    ]
    graph.node_renderer.data_source.data['nodessize'] = [
        x * 115 / (sqrt(g.number_of_nodes() + (np.mean(degree_sequence))))
        for x in graph.node_renderer.data_source.data['degree2']
    ]

    graph.node_renderer.data_source.data['my_fill_color'] = my_colors
    graph.edge_renderer.data_source.data['weight'] = weights
    graph.edge_renderer.data_source.add(colors, 'color')

    graph.node_renderer.glyph = Circle(size='nodesize',
                                       fill_alpha=0.85,
                                       fill_color='my_fill_color')
    graph.node_renderer.selection_glyph = Circle(size=10,
                                                 fill_alpha=0.8,
                                                 fill_color='red')
    graph.node_renderer.hover_glyph = Circle(size=10,
                                             fill_alpha=0.8,
                                             fill_color='yellow')

    graph.edge_renderer.glyph = MultiLine(line_width=3,
                                          line_alpha=0.8,
                                          line_color='color')
    graph.edge_renderer.selection_glyph = MultiLine(line_width=4,
                                                    line_alpha=0.8,
                                                    line_color='red')
    graph.edge_renderer.hover_glyph = MultiLine(line_width=4,
                                                line_alpha=0.8,
                                                line_color='yellow')
    graph.edge_renderer.glyph.line_width = {'field': 'weight'}

    graph.selection_policy = NodesAndLinkedEdges()
    graph.inspection_policy = NodesAndLinkedEdges()

    return graph
Exemplo n.º 8
0
	def network_total_following(self, user_dict, n_neighbors=5):
		graph = nx.Graph()
		self.add_nodes(graph, user_dict)
		self.add_edges(graph, user_dict)
		for node in list(graph.nodes()):
			if len(list(graph.neighbors(node))) < n_neighbors:
				graph.remove_node(node)
		plot = Plot(
			plot_width=1140,
			plot_height=720,
			x_range=Range1d(-1.1,1.1),
			y_range=Range1d(-1.1,1.1))
		plot.add_tools(
			HoverTool(tooltips=[('User','@name'),
				('Neighbors', '@neighbors')],
				line_policy='nearest'),
			TapTool(),
			BoxSelectTool(),
			PanTool(),
			WheelZoomTool(),
			ResetTool())
		graph_render = from_networkx(graph, nx.spring_layout, scale=2.5, center=(0,0))
		graph_render.node_renderer.data_source.data['name'] = list(graph.nodes())
		list_edges = self.get_list_of_edges(graph)
		graph_render.node_renderer.data_source.data['neighbors'] = list_edges
		mapper = linear_cmap('neighbors', palette=Plasma11, low=min(list_edges), high=max(list_edges))
		graph_render.node_renderer.glyph = Circle(
			size=10,
			fill_color=mapper)
		graph_render.node_renderer.hover_glyph = Circle(
			size=200,
			fill_color=mapper)
		graph_render.node_renderer.selection_glyph = Circle(
			size=200,
			fill_color=mapper)
		graph_render.edge_renderer.glyph = MultiLine(
			line_color=Greys4[2],
			line_alpha=0.3,
			line_width=1)
		graph_render.edge_renderer.hover_glyph = MultiLine(
			line_color=Greys4[1],
			line_width=2)
		graph_render.edge_renderer.selection_glyph = MultiLine(
			line_color=Greys4[0],
			line_width=3)
		graph_render.selection_policy = NodesAndLinkedEdges()
		graph_render.inspection_policy = NodesAndLinkedEdges()
		plot.renderers.append(graph_render)
		show(plot)
Exemplo n.º 9
0
def create_graph_rendrer(threshold, df, graph_df):
    plot_new = Plot(plot_width=1100,
                    plot_height=800,
                    x_range=Range1d(-1.1, 1.1),
                    y_range=Range1d(-1.1, 1.1))
    plot_new.title.text = "Dash-Graph"

    color_dict = {}

    for i in range(1, df['UserID'].max() + 1):
        color_dict[i] = df.groupby('UserID').groups[i].size * 1.9

    pal_hex_lst = bokeh.palettes.viridis(21)
    mapper = LinearColorMapper(palette=pal_hex_lst, low=0, high=21)

    G = create_graph(graph_df, threshold, True)

    # add graph's attributes
    node_size = {k: ((5 * v) + 5) for k, v in G.degree()}
    nx.set_node_attributes(G, color_dict, 'node_color')
    nx.set_node_attributes(G, node_size, 'node_size')
    graph_renderer = from_networkx(G, nx.spring_layout)
    graph_renderer.node_renderer.glyph = Circle(size='node_size',
                                                fill_color={
                                                    'field': 'node_color',
                                                    'transform': mapper
                                                })
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="black",
                                                   line_alpha=0.8,
                                                   line_width=0.5)
    graph_renderer.selection_policy = NodesAndLinkedEdges()

    plot.renderers.append(graph_renderer)
def plot_subgraph(  onto_graph:nx.Graph, node_subset:Union[List[str],Set[str]],
                    in_IPython:bool=False):
    """
    """
    G = onto_graph.subgraph(node_subset)
    # Show with Bokeh
    plot = Plot(plot_width=1600, plot_height=800,
                x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))

    plot.title.text = "Graph Interaction Demonstration"

    node_hover_tool = HoverTool(tooltips=[("index", "@index"), ("club", "@club")])
    plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(), TapTool(), BoxSelectTool(), PanTool())

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

    graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_alpha=0.8, line_width=1)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
    #graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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


    plot.renderers.append(graph_renderer)

    #output_file("interactive_graphs.html")
    if in_IPython: output_notebook()

    show(plot)
Exemplo n.º 11
0
def style(graph):
    global node_indices,plot
    graph.node_renderer.data_source.add(Spectral5, 'color') # kolory node'ow
    graph.node_renderer.glyph = Oval(height=0.6, width=0.6, fill_color='color') # ksztalt node'a
    graph_layout = dict(zip(node_indices, zip(x, y))) # layout
    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)
    graph.inspection_policy = NodesAndLinkedEdges()
Exemplo n.º 12
0
    def get_graph(self):

        start = self.data['Start']
        end = self.data['End']
        fl = self.data['Index']
        fio = self.data['FIO']
        node_indices = end.append(pd.Series(pd.Series.unique(self.data['Start'])), ignore_index=True)
        #fl = pd.Series.unique(self.data['Index'])
        #fl = self.data['Index']
        #edges = zip(start, end)
        edges =[]
        for i in range(len(start)):
                edges.append(tuple([start[i], end[i], {'OGRNIP': str(fl[i]) + " - " + str(fio[i])}]))
        G = nx.Graph()
        G.add_nodes_from(node_indices)
        G.add_edges_from(edges)
        #print(G.adj.items())
        #print(G.edges.data())
        ogrns =[]
        for item in G.edges.data():
            #print(item[2]['OGRNIP'])
            ogrns.append(item[2]['OGRNIP'])
        tooltips=[
            #("index", "$index"),
            #("(x,y)", "($x, $y)"),
            ("1 - ОГРН", "@start"),
            ("2 - ОГРН", "@end"),
            ("ФЛ", "@OGRNIP"),
            #("Моя подсказка", "@end"),
        ]
        # hover = HoverTool(tooltips=tooltips)

        p = figure(plot_width=self.width, plot_height=self.height, x_range=(-3.1, 3.1), y_range=(-3.1, 3.1),
                   x_axis_type=None, y_axis_type=None, tools=[],
                   min_border=0, outline_line_color="white")

        # p.add_tools(WheelZoomTool())
        # p.add_tools(PanTool())
        p.add_tools(HoverTool(tooltips=tooltips), TapTool(), BoxSelectTool(), WheelZoomTool(), PanTool())

        #graph = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0))
        graph = from_networkx(G, nx.spring_layout, scale=2, center=(0, 0))
        graph.node_renderer.glyph = Circle(size=5, fill_color="gray")
        graph.node_renderer.hover_glyph = Circle(size=5, fill_color="red")
        graph.node_renderer.selection_glyph = Circle(size=5, fill_color="green")

        graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=1)
        graph.edge_renderer.selection_glyph = MultiLine(line_color="gray", line_width=1)
        graph.edge_renderer.hover_glyph = MultiLine(line_color="gray", line_width=1)

        graph.selection_policy = NodesAndLinkedEdges()
        graph.inspection_policy = EdgesAndLinkedNodes()
        # print(graph.node_renderer.data_source.data)
        # print(graph.edge_renderer.data_source.data)
        graph.edge_renderer.data_source.data['OGRNIP'] = ogrns
        #print(graph.edge_renderer.data_source.data)
        #print(graph.node_renderer.data_source.data)
        p.renderers.append(graph)

        return p
Exemplo n.º 13
0
def test_html(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')
    G = nx.karate_club_graph()
    plot = Plot(plot_width=400, plot_height=400,
                x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))
    plot.title.text = "Graph Interaction Demonstration"

    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.glyph = Circle(size=15, fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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

    plot.renderers.append(graph_renderer)

    output_file("interactive_graphs.html")
    show(plot)
Exemplo n.º 14
0
def style(graph):
    global node_indices,plot
    graph.node_renderer.data_source.add(["#99d594"]*(len(node_indices)), 'color') # kolory node'ow
    graph.node_renderer.glyph = Oval(height=BokehParams.point_height, width=BokehParams.point_width, fill_color='color') # ksztalt node'a
    graph_layout = dict(zip(node_indices, zip(x, y))) # layout
    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)
    graph.inspection_policy = NodesAndLinkedEdges()
Exemplo n.º 15
0
def graphNetwork(data, tags):
    G = nx.from_numpy_matrix(data)
    graph_plot = Plot(plot_width=800,
                      plot_height=800,
                      x_range=Range1d(-1.1, 1.1),
                      y_range=Range1d(-1.1, 1.1))
    graph_plot.title.text = "Graph.\nTotal Nodes: %i\nTotal Edges: %i" % (
        G.number_of_nodes(), G.number_of_edges())

    node_hover_tool = HoverTool(tooltips=[("hashtag", "@hashtag")])
    graph_plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(),
                         WheelZoomTool(), BoxSelectTool())

    graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))
    graph_renderer.node_renderer.glyph = Circle(size=15, fill_color='#277bb6')
    graph_renderer.node_renderer.hover_glyph = Circle(size=18,
                                                      fill_color='#E84A5F')
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="gray",
                                                   line_alpha=0.8,
                                                   line_width=0.5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color='#e09e8f',
                                                         line_width=3)
    graph_renderer.inspection_policy = NodesAndLinkedEdges()
    graph_renderer.selection_policy = EdgesAndLinkedNodes()
    graph_renderer.node_renderer.data_source.data['hashtag'] = tags

    graph_plot.renderers.append(graph_renderer)

    output_file("interactive_graphs.html")

    show(graph_plot)
Exemplo n.º 16
0
def create_cit_map(nodes, edges):

    G = nx.DiGraph()

    G.add_nodes_from(nodes)

    G.add_edges_from(edges)

    plot = Plot(plot_width=800, plot_height=800, x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
    plot.title.text = ""

    graph_renderer = from_networkx(G, nx.kamada_kawai_layout, scale=1)

    graph_renderer.node_renderer.glyph = Circle(size=15)
    graph_renderer.node_renderer.selection_glyph = Circle(size=15)
    graph_renderer.node_renderer.hover_glyph = Circle(size=15)

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_width=5)

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

    pos = graph_renderer.layout_provider.graph_layout
    x,y=zip(*pos.values())
    source = ColumnDataSource({'x':x,'y':y,'names': nodes})
    labels = LabelSet(x='x', y='y', text='names', source=source, level='glyph', x_offset=5, y_offset=5)

    plot.renderers.append(labels)

    plot.renderers.append(graph_renderer)
    #plot.add_layout(labels)
    output_file("interactive_graphs.html")
    show(plot)
Exemplo n.º 17
0
    def show(self):
        '''Paint the graph object'''

        plot = figure(
            plot_width=self.width,
            plot_height=self.height,
            title=self.title,
            x_range=(0, self.width),
            y_range=(0, self.height)
        )
        plot.axis.visible = False
        plot.grid.visible = False
        plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
        self.define_vertex_shape()
        self.define_edges()
        self.bokeh_graph.selection_policy = NodesAndLinkedEdges()
        self.bokeh_graph.inspection_policy = EdgesAndLinkedNodes()

        self.map_to_coordinates()

        # print('\nSHAPE', self.bokeh_graph.node_renderer.data_source.data)
        # print('\nEDGES', self.bokeh_graph.edge_renderer.data_source.data)
        # print('\nCOORDINATES', self.bokeh_graph.layout_provider)
        # INCLUDE the Graph in the Plot
        plot.renderers.append(self.bokeh_graph)
        # GENERATE PLOT HTML FILE AND OPEN IN BROWSER
        output_file('./graph.html')
        show(plot)
def draw_network(t):

    # We could use figure here but don't want all the axes and titles
    plot = Plot(x_range=Range1d(-6, 6), y_range=Range1d(-6, 6))

    # Create a Bokeh graph from the NetworkX input using nx.spring_layout
    graph = from_networkx(graphs[t]["graph"],
                          nx.layout.fruchterman_reingold_layout,
                          scale=5,
                          center=(0, 0))
    plot.renderers.append(graph)

    graph.node_renderer.data_source.data['colors'] = graphs[t]["colors"]
    graph.node_renderer.data_source.data['sizes'] = graphs[t]["node_sizes"]
    graph.node_renderer.glyph = Circle(size='sizes', fill_color='colors')
    graph.edge_renderer.glyph = MultiLine(line_alpha=1.6, line_width=4)

    # green hover for both nodes and edges
    graph.node_renderer.hover_glyph = Circle(size='sizes',
                                             fill_color='#abdda4')
    graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4',
                                                line_width=8)

    # When we hover over nodes, highlight adjecent edges too
    graph.inspection_policy = NodesAndLinkedEdges(
    )  # can we change this so edges can be hovered over too?

    TOOLTIPS = [
        ("Demand", "@demand"),
        ("Type", "@node_type"),
    ]

    plot.add_tools(HoverTool(tooltips=TOOLTIPS))

    return plot
Exemplo n.º 19
0
def create_graph():
    #Find the layout and color choice
    if radio_layout.active == 0:
        lay = 'WDegreepos'
    elif radio_layout.active == 1:
        lay = 'bwcentralpos'
    else:
        lay = 'ccentralpos'

    if radio_color.active == 0:
        col = 'DegCol'
    elif radio_color.active == 1:
        col = 'Colbw'
    elif radio_color.active == 2:
        col = 'friend'
    elif radio_color.active == 3:
        col = 'reviewcount'
    else:
        col = 'comprank'

    # Create Network view
    graph = GraphRenderer()
    graph.node_renderer.data_source.data = nodes_df(G, col)
    graph.edge_renderer.data_source.data = edges_df(G)
    graph.node_renderer.glyph = Circle(size='size',
                                       fill_color='Col',
                                       line_color="black",
                                       line_alpha=0.1,
                                       fill_alpha=1)
    graph.edge_renderer.glyph = MultiLine(line_alpha='alpha',
                                          line_width=0.1,
                                          line_color="#d8b7a4")
    graph_layout = dict(nx.get_node_attributes(G, lay))
    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

    # Glyph properties on selection
    graph.selection_policy = NodesAndLinkedEdges()
    graph.inspection_policy = EdgesAndLinkedNodes()
    graph.node_renderer.selection_glyph = Circle(size=12,
                                                 fill_color='#0A5EB6',
                                                 line_color="#002217")
    graph.edge_renderer.selection_glyph = MultiLine(line_color="#2972BE",
                                                    line_width=0.5,
                                                    line_alpha=0.4)

    # Adding graph to plot
    plot = figure(title="Yelp Users Layout",
                  x_range=(-6.5, 6.5),
                  y_range=(-6.5, 6.5),
                  plot_width=525,
                  plot_height=525,
                  toolbar_location="above")
    plot.outline_line_alpha = 0
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = None
    plot.xaxis.visible = False
    plot.yaxis.visible = False
    plot.renderers.append(graph)  # Adding graph

    return row(plot)
Exemplo n.º 20
0
    def _setup_graph_renderer(self, circle_size, draw_components):
        # The renderer will have the actual logic for drawing
        graph_renderer = GraphRenderer()
        # Saving vertices in an arbitrary but persistent order
        self.vertex_list = list(self.graph.vertices.keys())

        # Add the vertex data as instructions for drawing nodes
        graph_renderer.node_renderer.data_source.add(
            [vertex.label for vertex in self.vertex_list], 'index')
        colors = (self._get_connected_component_colors()
                  if draw_components else self._get_random_colors())
        graph_renderer.node_renderer.data_source.add(colors, 'color')
        # And circles
        graph_renderer.node_renderer.glyph = Circle(size=circle_size,
                                                    fill_color='color')

        graph_renderer.node_renderer.hover_glyph = Circle(
            size=circle_size, fill_color=Category20[20][9])
        graph_renderer.node_renderer.selection_glyph = Circle(
            size=circle_size, fill_color=Category20[20][6])

        # Add the edge [start, end] indices as instructions for drawing edges
        graph_renderer.edge_renderer.data_source.data = self._get_edge_indexes(
        )
        self.randomize()  # Randomize vertex coordinates, and set as layout
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=self.pos)

        # Attach the prepared renderer to the plot so it can be shown
        graph_renderer.selection_policy = NodesAndLinkedEdges()
        graph_renderer.inspection_policy = EdgesAndLinkedNodes()
        self.plot.renderers.append(graph_renderer)
        print(graph_renderer.node_renderer)
        tool = PointDrawTool(renderers=[graph_renderer.node_renderer])
        self.plot.add_tools(tool)
Exemplo n.º 21
0
def create_transactor_figure(G):
    plot = Plot(plot_width=800,
                plot_height=600,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    plot.title.text = "Transactor Visualization"

    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool(),
                   WheelZoomTool(), PanTool())

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

    graph_renderer.node_renderer.glyph = Circle(size=4,
                                                fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=4, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=4,
                                                      fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.8,
                                                   line_width=3)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=3)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=3)

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

    plot.renderers.append(graph_renderer)

    return plot
Exemplo n.º 22
0
def draw_graph(plot, G):
    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
    graph = from_networkx(G,
                          nx.spring_layout,
                          pos=node_positions,
                          fixed=node_positions.keys())

    graph.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
    graph.node_renderer.selection_glyph = Circle(size=15,
                                                 fill_color=Spectral4[2])
    graph.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

    graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                          line_alpha=0.8,
                                          line_width=5)
    graph.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2],
                                                    line_width=5)
    graph.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1],
                                                line_width=5)

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

    plot.renderers.append(graph)
    return plot
Exemplo n.º 23
0
def Grouped(doc):
    args = doc.session_context.request.arguments
    file = args.get('file')[0]
    file = str(file.decode('UTF-8'))

    with open("media/" + file) as data:
        csv_reader = csv.reader(data, delimiter=';')
        processedData = list(csv_reader)
        header = processedData[0]
        g = nx.Graph()
        for i in range(1, len(processedData[0])):
            g.add_node(processedData[0][i])
        for i in range(1, len(processedData)):
            for e in range(i, len(processedData[i])):
                try:
                    value = int(processedData[i][e])
                    if value > 0:
                        g.add_edge(header[i], header[e], weight=value)
                except:
                    pass

        TOOLTIPS = [("Name", "@index")]
        plot = figure(title="",
                      x_range=(-2.2, 2.2),
                      y_range=(-1.1, 1.1),
                      tooltips=TOOLTIPS,
                      plot_width=1400,
                      plot_height=700)
        graph = from_networkx(g, nx.spring_layout, scale=2, center=(0, 0))

        graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                              line_width=2)
        graph.edge_renderer.selection_glyph = MultiLine(
            line_color=Spectral4[2], line_width=2)
        graph.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1],
                                                    line_width=2)

        graph.node_renderer.glyph = Circle(fill_color=Spectral4[0])
        graph.node_renderer.selection_glyph = Circle(fill_color=Spectral4[2])
        graph.node_renderer.hover_glyph = Circle(fill_color=Spectral4[1])

        graph.selection_policy = NodesAndLinkedEdges()
        graph.inspection_policy = NodesAndLinkedEdges()
        plot.renderers.append(graph)
        doc.add_root(column(plot))
Exemplo n.º 24
0
    def drawgraph(self, ds, filterMin, filterMax, layout):
        G = nx.Graph()  # create an empty graph with no nodes and no edges

        # nodes = []
        # for i in range(len(ds.getNodes())):
        #     nodes.append([])
        #     # print(ds.getNodes()[i].getName())
        #     for j in range(len(ds.getNodes())):
        #         nodes[i].append(ds.getNodes()[i].getLinks()[j][1])
        #         # print("   " + str(ds.getNodes()[i].getLinks()[j][1]))

        # ds.toMinSpanTree()
        nodes = ds.getDoubleList(filterMin, filterMax, False)

        x = filterMin

        adj = np.array(nodes)
        G = nx.from_numpy_matrix(adj)

        for i in range(len(G.node)):
            G.node[i]['name'] = ds.getNames()[i]
        #pos = nx.drawing.layout.circular_layout(G, 1, None, 2)

        #nx.draw_networkx(G, pos, with_labels=True)
        # pt.show()
        #plt.show()
        plot = Plot(plot_width=500, plot_height=500,
                    x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))

        node_hover_tool = HoverTool(tooltips=[("Name of this node", "@name")])

        # plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())
        plot.add_tools(node_hover_tool, TapTool(), BoxSelectTool(), BoxZoomTool(), UndoTool(), RedoTool(), SaveTool(),
                       ResetTool())
        plot.toolbar_location = 'left'
        if layout == 0:
            graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0))
        elif layout == 1:
            graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))
        else:
            graph_renderer = from_networkx(G, nx.random_layout)
        graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
        graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
        graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

        graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
        graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
        graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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

        plot.renderers.append(graph_renderer)

        output_file("interactive_graphs.html")
        return plot
Exemplo n.º 25
0
def do_plot_graph(nodes, edges, colors, sizes, description, output_plot):
    G = nx.Graph()
    G.add_nodes_from(nodes)
    G.add_edges_from(edges)

    hover = HoverTool(tooltips=[
        ("name", "@index")])

    plot = figure(plot_width=900, plot_height=900, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1),
                  tools=[hover, BoxZoomTool(), ResetTool(), PanTool(),
                         WheelZoomTool(), "tap"],
                  title=output_plot)
    plot.toolbar.logo = None

    plot.title.text = description

    url_protein = "https://www.ncbi.nlm.nih.gov/gene/?term=@index"
    taptool = plot.select(type=TapTool)
    taptool.callback = OpenURL(url=url_protein)

    graph_renderer = from_networkx(G, nx.fruchterman_reingold_layout, scale=1)

    source = ColumnDataSource({'index': nodes, 'fill_color': colors, 'size': sizes})
    graph_renderer.node_renderer.data_source = source
    graph_renderer.node_renderer.glyph = Circle(size="size", fill_color="fill_color", line_width=0,
                                                line_color="fill_color")

    graph_renderer.node_renderer.selection_glyph = Circle(size="size", fill_color=Spectral4[2], line_width=0,
                                                          line_color=Spectral4[1])
    graph_renderer.node_renderer.hover_glyph = Circle(size="size", fill_color=Spectral4[1], line_width=0,
                                                      line_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=1, line_width=0.2)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=1)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=1)

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

    plot.renderers.append(graph_renderer)

    output_file(output_plot)
Exemplo n.º 26
0
def plot_bokeh_network_i(G,
                         id,
                         layout=nx.circular_layout,
                         output="testing.html"):
    plot = Plot(plot_width=400,
                plot_height=400,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    plot.title.text = "Graph Interaction Demonstration"
    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool(),
                   WheelZoomTool())

    graph_renderer = from_networkx(G, layout, scale=1, center=(0, 0))

    graph_renderer.node_renderer.glyph = Circle(size=15,
                                                fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=15, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=15,
                                                      fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.8,
                                                   line_width=5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=5)

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

    x, y = zip(*graph_renderer.layout_provider.graph_layout.values())

    node_labels = nx.get_node_attributes(G, 'hostname')

    source = ColumnDataSource({
        'x':
        x,
        'y':
        y,
        'label': [node_labels[id[i]] for i in range(len(x))]
    })

    labels = LabelSet(x='x',
                      y='y',
                      text='label',
                      source=source,
                      background_fill_color='white')

    plot.renderers.append(graph_renderer)

    output_file(output)
    save(plot)
Exemplo n.º 27
0
def create_figure(G, ntx):
    plot = Plot(plot_width=800,
                plot_height=600,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    #plot.title.text = "BTC Block Visualization"

    citation = Label(x=0, y=-20, x_units='screen', y_units='screen',
                text='This block contains '+str(ntx)+\
                 ' transactions between '+str(len(G.nodes()))+\
                 ' addresses. The most active address transacted with '+str(max(list(dict(G.degree()).values())))+\
                 ' addresses.',
                render_mode='css',
                border_line_color='red', border_line_alpha=1.0,
                background_fill_color='white', background_fill_alpha=1.0)

    #citation = Label(x=40, y=0, x_units='screen', y_units='screen',
    #             text='There were '+str(ntx)+' transactions total. The most active transactor was involved in '+str(max(list(dict(G.degree()).values())))+' transactions.',
    #             render_mode='css',
    #             border_line_color='black', border_line_alpha=1.0,
    #             background_fill_color='white', background_fill_alpha=1.0)

    plot.add_layout(citation)

    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool(),
                   WheelZoomTool(), PanTool())

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

    graph_renderer.node_renderer.glyph = Circle(size=4,
                                                fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=4, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=4,
                                                      fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.8,
                                                   line_width=3)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=3)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=3)

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

    plot.renderers.append(graph_renderer)

    return plot
Exemplo n.º 28
0
def _network_figure(p, nodes, graph):
    palette = list(reversed(Magma11))
    color_mapper = LinearColorMapper(palette=palette,
                                     low=nodes["centrality"].min(),
                                     high=nodes["centrality"].max())
    p.add_tools(
        HoverTool(tooltips=[("Name", "@index"), ("Centrality",
                                                 "@centrality")]), TapTool(),
        BoxSelectTool())

    p.xaxis.visible = False
    p.yaxis.visible = False
    p.grid.visible = False

    renderer = from_networkx(graph, nx.kamada_kawai_layout)

    renderer.node_renderer.data_source.add(nodes["centrality"], "centrality")
    renderer.node_renderer.glyph = Circle(size=15,
                                          fill_color={
                                              "field": "centrality",
                                              "transform": color_mapper
                                          })
    renderer.node_renderer.selection_glyph = Circle(size=15,
                                                    fill_color=Spectral4[2])
    renderer.node_renderer.hover_glyph = Circle(size=15,
                                                fill_color=Spectral4[1])

    renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                             line_alpha=0.8,
                                             line_width=2)
    renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2],
                                                       line_width=4)
    renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1],
                                                   line_width=4)

    renderer.selection_policy = NodesAndLinkedEdges()
    renderer.inspection_policy = NodesAndLinkedEdges()

    p.renderers.append(renderer)
    return p
Exemplo n.º 29
0
def visual():
    '''
    visualze whole graph
    '''
    nx = networkx.Graph()
    color_movie = Spectral4[0]
    color_actor = Spectral4[3]

    for aid in g.all_actors:
        inf = g.all_actors[aid]['age']
        nx.add_node(aid, type = 'Actor', item_name = aid, info = "Age: " + str(inf), color = color_actor, size = 10)


    for mid in g.all_movies:
        # if g.all_movies[mid]['actors'] == []:
        #     continue
        inf = g.all_movies[mid]['box_office']
        nx.add_node(mid, type = 'Movie', item_name = mid,info = "Box Office: " + str(inf), color = color_movie, size = 15)

    for mid in g.all_movies:
        movie = g.all_movies[mid]
        for aid in movie['actors']:
            if aid not in g.all_actors:
                continue
            nx.add_edge(mid, aid)

    for aid in g.all_actors:
        for mid in g.all_actors[aid]['movies']:
            if mid not in g.all_movies:
                continue
            nx.add_edge(aid, mid)


    p = Plot(plot_width=1200, plot_height=1200,
                x_range=Range1d(-3, 3), y_range=Range1d(-3, 3))
    p.title.text = "Visualization of the graph"
    p.add_tools(HoverTool(tooltips=[("Name", "@item_name"), ("Info", "@info")]), TapTool(), BoxSelectTool())

    graph_renderer = from_networkx(nx, networkx.spring_layout, scale=7, center=(0, 0))
    graph_renderer.node_renderer.glyph = Circle(size='size', fill_color='color')
    graph_renderer.node_renderer.selection_glyph = Circle(size='size', fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size='size', fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=1)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color='#440154', line_width=1)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=1)

    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_renderer.inspection_policy = NodesOnly()
    p.renderers.append(graph_renderer)
    script, div = components(p)
    return render_template("visualization.html", script=script, div=div)
Exemplo n.º 30
0
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)