Beispiel #1
0
    def drawGraph(self):
        graph = self.graph
        N = len(graph.vertices)
        node_indices = list(graph.vertices)

        plot = figure(title="Graph Layout Demonstration",
                      x_range=(-1.1, 10.1),
                      y_range=(-1.1, 10.1),
                      tools='',
                      toolbar_location=None)

        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        graph_renderer.node_renderer.data_source.add(
            [graph.vertices[vertex_id].color for vertex_id in graph.vertices],
            'color')
        graph_renderer.node_renderer.glyph = Circle(radius=0.5,
                                                    fill_color='color')

        start_indices = []
        end_indices = []

        for vertex_id in graph.vertices:  #here we're looking at the keys of our vertex dictionary
            for edge_end in graph.vertices[vertex_id].edges:
                start_indices.append(vertex_id)
                end_indices.append(edge_end)

        graph_renderer.edge_renderer.data_source.data = dict(
            start=start_indices, end=end_indices)

        ### start of layout code
        x = [graph.vertices[vertex_id].x for vertex_id in graph.vertices]
        y = [graph.vertices[vertex_id].y for vertex_id in graph.vertices]

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_renderer)

        labelSource = ColumnDataSource(
            data=dict(x=x,
                      y=y,
                      names=[
                          graph.vertices[vertex_id].value
                          for vertex_id in graph.vertices
                      ]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          source=labelSource,
                          render_mode='canvas')

        plot.add_layout(labels)

        output_file('graph1.html')
        show(plot)


# class BokehGraph:
#     """Class that takes a graph and exposes drawing methods."""
#     def __init__(self, graph):
#         self.graph = graph

#     def drawGraph(self):
#         pass

# #test
# graph1 = Graph()  # Instantiate your graph
# graph1.add_vertex(0)
# graph1.add_vertex(1)
# graph1.add_vertex(2)
# graph1.add_vertex(3)
# graph1.add_edge(0, 1)
# graph1.add_edge(0, 3)

# bokehGraph1 = BokehGraph(graph1)
# bokehGraph1.drawGraph()

# ###### Bookeh example for Visualizing Network Graphs (https://bokeh.pydata.org/en/latest/docs/user_guide/graph.html) ##########
# import math

# from bokeh.io import show, output_file
# from bokeh.plotting import figure
# # "Bokeh uses a separate LayoutProvider model in order to supply the coordinates of a graph in Cartesian space. Currently the only built-in provider is the StaticLayoutProvider model, which contains a dictionary of (x,y) coordinates for the nodes.""
# from bokeh.models import GraphRenderer, StaticLayoutProvider, Oval
# from bokeh.palettes import Spectral8

# N = 8
# node_indices = list(range(N))

# # figure class (imported above) creates a new Figure for plotting. class Figure(*ark, **kw) is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc.
# plot = figure(title='Graph Layout Demonstration', x_range=(-1.1,1.1), y_range=(-1.1,1.1),
#               tools='', toolbar_location=None)

# # GraphRenderer class: maintains separate sub-GlyphRenderers for the graph nodes and the graph edges. This allows for customizing the nodes by modifying the GraphRenderer’s node_renderer property.
# #   -edge_renderer attribute: Instance of GlyphRenderer class containing an MultiLine Glyph that will be rendered as the graph edges.
# #   -node_renderer attribute: Instance of GlyphRenderer class containing an XYGlyph (point-like Glyph) that will be rendered as the graph nodes.
# graph = GraphRenderer()

# # data_source attribute of Glyphrenderer: Local data source to use when rendering glyphs on the plot. Instance of the DataSource class. The DataSource class is a an abstract base class used to help organize the hierarchy of Bokeh model types. It is not useful to instantiate on its own.
# # Two requirements for data sources belonging to node_renderer and edge_renderer
# #   -The ColumnDataSource (i.e. a JSON dict that maps names to arrays of values) associated with the node sub-renderer must have a column named "index" that contains the unique indices of the nodes.
# #   -The ColumnDataSource associated with the edge sub-renderer has two required columns: "start" and "end". These columns contain the node indices of for the start and end of the edges.
# # ColumnDataSource is a bokeh class that maps names of columns to sequences or arrays. It's a fundamental data structure of Bokeh. Most plots, data tables, etc. will be driven by a ColumnDataSource.
# graph.node_renderer.data_source.add(node_indices, 'index')

# # spectral8 (a color palette) specifies the range of colors used for the plot markers
# graph.node_renderer.data_source.add(Spectral8, 'color')

# # specifies the shape and style of the plot markers (i.e. graph nodes in our case)
# # GlyphRenderer class attr glyph: Instance of Glyph class. Specifies glyph to render, in conjunction with the supplied data source and ranges.
# graph.node_renderer.glyph = Oval(height=0.1, width=0.2, fill_color='color')

# # The ColumnDataSource associated with the edge sub-renderer has two required columns: "start" and "end". These columns contain the node indices of for the start and end of the edges.
# # data attribute of ColumnDataSource class : Mapping of column names to sequences of data. The data can be, e.g, Python lists or tuples, NumPy arrays, etc.
# graph.edge_renderer.data_source.data = dict(
#     start=[0]*N,
#     end=node_indices)

# ### start of layout code
# # circ here is a list populated with the different angles of a circle (i.e. 0 to 2*pi)
# circ = [i*2*math.pi/8 for i in node_indices]
# x = [math.cos(i) for i in circ]
# y = [math.sin(i) for i in circ]

# # the zip() method: The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
# graph_layout = dict(zip(node_indices, zip(x, y)))

# # StaticLayoutProvider base class: bokeh.models.graphs.LayoutProvider (abstract data type. not useful on its own.)
# # graph_layout attribute of StaticLayoutProvider: The coordinates of the graph nodes in cartesian space. The dictionary keys correspond to a node index and the values are a two element sequence containing the x and y coordinates of the node. (property type: Dict ( Either ( String , Int ), Seq ( Any ) ))
# # By default the StaticLayoutProvider will draw straight-line paths between the supplied node positions. In order to supply explicit edge paths you may also supply lists of paths to the edge_renderer bokeh.models.sources.ColumnDataSource. The StaticLayoutProvider will look for these paths on the "xs" and "ys" columns of the data source. Note that these paths should be in the same order as the "start" and "end" points.
# graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

# # plot here is an instantiation of the Figure class (A subclass of Plot that simplifies plot creation with default axes, grids, tools, etc.)
# # renderers is an attribute of Plot. Description:A list of all renderers for this plot, including guides and annotations in addition to glyphs and markers. property type: List ( Instance ( Renderer ) ). Recall that Renderer is an abstract base class used to help organize the hierarchy of Bokeh model types. It is not useful to instantiate on its own.
# plot.renderers.append(graph)

# # output_file(): Configures the default output state to generate output saved to a file when show() is called. (https://bokeh.pydata.org/en/latest/docs/reference/io.html#bokeh.io.output_file)
# output_file('graphEx1.html')
# # show(): Immediately displays a Bokeh object or application. (https://bokeh.pydata.org/en/latest/docs/reference/io.html#bokeh.io.show)
# show(plot)

# ############## Attempt 1 ########################
# # NOTE: I didn't finish this first attempt at the BokehGraph class. In interest of time
# # I decided to pause and implement the solution code from graph lecture day 2.
# class BokehGraph:
#     """Class that takes a graph and exposes drawing methods."""
#     def __init__(self, graph):
#         self.graph = graph

#     def drawGraph(self):
#         graph = self.graph
#         N = len(graph.vertices)
#         node_indices = list()
#         for i in graph.vertices:
#             node_indices.append(i.value)

#         # figure class (imported above) creates a new Figure for plotting. class Figure(*ark, **kw) is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc.
#         plot = figure(title = 'Adrian\'s Graph Demo', x_range = (-10,10), y_range = (-10,10))

#         # GraphRenderer class: maintains separate sub-GlyphRenderers for the graph nodes and the graph edges. This allows for customizing the nodes by modifying the GraphRenderer’s node_renderer property.
#         #   -edge_renderer attribute: Instance of GlyphRenderer class containing an MultiLine Glyph that will be rendered as the graph edges.
#         #   -node_renderer attribute: Instance of GlyphRenderer class containing an XYGlyph (point-like Glyph) that will be rendered as the graph nodes.
#         graphRenderer = GraphRenderer()

#         # data_source attribute of Glyphrenderer: Local data source to use when rendering glyphs on the plot. Instance of the DataSource class. The DataSource class is a an abstract base class used to help organize the hierarchy of Bokeh model types. It is not useful to instantiate on its own.
#         # Two requirements for data sources belonging to node_renderer and edge_renderer
#         #   -The ColumnDataSource (i.e. a JSON dict that maps names to arrays of values) associated with the node sub-renderer must have a column named "index" that contains the unique indices of the nodes.
#         #   -The ColumnDataSource associated with the edge sub-renderer has two required columns: "start" and "end". These columns contain the node indices of for the start and end of the edges.
#         # ColumnDataSource is a bokeh class that maps names of columns to sequences or arrays. It's a fundamental data structure of Bokeh. Most plots, data tables, etc. will be driven by a ColumnDataSource.
#         graphRenderer.node_renderer.data_source.add(node_indices, 'index')

#         # # spectral8 (a color palette) specifies the range of colors used for the plot markers
#         # graphRenderer.node_renderer.data_source.add(Spectral8, 'color')

#         # specifies the shape and style of the plot markers (i.e. graph nodes in our case)
#         # GlyphRenderer class attr glyph: Instance of Glyph class. Specifies glyph to render, in conjunction with the supplied data source and ranges.
#         graphRenderer.node_renderer.glyph = Circle(radius=0.2)

#         # The ColumnDataSource associated with the edge sub-renderer has two required columns: "start" and "end". These columns contain the node indices of for the start and end of the edges.
#         # data attribute of ColumnDataSource class : Mapping of column names to sequences of data. The data can be, e.g, Python lists or tuples, NumPy arrays, etc.
#         start_indices = []
#         end_indices = []

#         for vertex in graph.vertices:
#             for edge_end in graph.vertices[vertex].adjVertices:
#                 start_indices.append(vertex.value)
#                 end_indices.append(edge_end.value)
#             # print(start_indices)
#             # print(end_indices)

#         # print(start_indices)
#         # print(end_indices)

#         graphRenderer.edge_renderer.data_source.data = dict(
#             start=start_indices,
#             end=end_indices)

#         ### start of layout code
#         x = [graph.vertices[vertex].x for vertex in graph.vertices]
#         y = [graph.vertices[vertex].y for vertex in graph.vertices]

#         x = []
#         y = []

#         for vertex in graph.vertices:
#             x.append(vertex.x)
#             y.append(vertex.y)

#         # the zip() method: The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
#         graph_layout = dict(zip(node_indices, zip(x, y)))

#         # StaticLayoutProvider base class: bokeh.models.graphs.LayoutProvider (abstract data type. not useful on its own.)
#         # graph_layout attribute of StaticLayoutProvider: The coordinates of the graph nodes in cartesian space. The dictionary keys correspond to a node index and the values are a two element sequence containing the x and y coordinates of the node. (property type: Dict ( Either ( String , Int ), Seq ( Any ) ))
#         # By default the StaticLayoutProvider will draw straight-line paths between the supplied node positions. In order to supply explicit edge paths you may also supply lists of paths to the edge_renderer bokeh.models.sources.ColumnDataSource. The StaticLayoutProvider will look for these paths on the "xs" and "ys" columns of the data source. Note that these paths should be in the same order as the "start" and "end" points.
#         graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

#         plot.renderers.append(graphRenderer)
#         output_file('graphEx1.html')
#         show(plot)
Beispiel #2
0
        end_indices.append(edge_end)
print(start_indices)
print(end_indices)

graph_renderer.edge_renderer.data_source.data = dict(start=start_indices,
                                                     end=end_indices)

# start of layout code
grid = [int(v) for v in graph.vertices]
x = [2 * (i // 3) for i in grid]
y = [2 * (i % 3) for i in grid]
# x = [i for i in grid]
# y = [i ** 2 for i in grid]

graph_layout = dict(zip(node_indices, zip(x, y)))
graph_renderer.layout_provider = StaticLayoutProvider(
    graph_layout=graph_layout)

plot.renderers.append(graph_renderer)

labelSource = ColumnDataSource(data=dict(x=x, y=y, names=grid))
labels = LabelSet(x='x',
                  y='y',
                  text='names',
                  level='glyph',
                  text_align='center',
                  text_baseline='middle',
                  source=labelSource,
                  render_mode='canvas')

plot.add_layout(labels)
Beispiel #3
0
    def draw(self):
        graph = self.graph

        N = len(graph.vertices)
        node_indices = list(graph.vertices.keys())

        plot = figure(title="Graph Layout Demonstration",
                      x_range=(-6, 6),
                      y_range=(-6, 6),
                      tools="",
                      toolbar_location=None)

        graph_render = GraphRenderer()

        graph_render.node_renderer.data_source.add(node_indices, 'index')
        node_colors = []
        for vert in graph.vertices:
            node_colors.append(graph.vertices[vert].color)
        # node_colors = ['red'] * int(N / 2)
        # another_color = ['blue'] * int(N/2)
        # node_colors.extend(another_color)
        # if N % 2 != 0:
        #     node_colors.extend(['green'])
        graph_render.node_renderer.data_source.add(node_colors, 'color')
        graph_render.node_renderer.glyph = Circle(radius=0.25,
                                                  fill_color="color")

        edge_start = []
        edge_end = []

        for vert_id in node_indices:
            for v in graph.vertices[vert_id].edges:
                edge_start.append(vert_id)
                edge_end.append(v)

        graph_render.edge_renderer.data_source.data = dict(start=edge_start,
                                                           end=edge_end)

        ### start of layout code
        # circ = [i*2*math.pi/8 for i in node_indices]
        # x = [math.cos(i) for i in circ]
        # y = [math.sin(i) for i in circ]
        x = []
        y = []
        for vert_id in node_indices:
            vertex = graph.vertices[vert_id]
            x.append(vertex.x)
            y.append(vertex.y)

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_render.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_render)

        labelSource = ColumnDataSource(
            data=dict(x=x, y=y, names=[vert_id for vert_id in graph.vertices]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          source=labelSource,
                          render_mode='canvas')

        plot.add_layout(labels)

        output_file("graph_demo.html")
        # output_file("graph.html")
        show(plot)


# graph = Graph()  # Instantiate your graph
# graph.add_vertex('0')
# graph.add_vertex('1')
# graph.add_vertex('2')
# graph.add_vertex('3')
# graph.add_vertex('4')
# graph.add_edge('0', '1')
# graph.add_edge('0', '3')
# graph.add_edge('3', '4')

# bg = BokehGraph(graph)
# bg.draw()
Beispiel #4
0
    def _init_glyphs(self, plot, element, ranges, source):
        # Get data and initialize data source
        style = self.style[self.cyclic_index]
        data, mapping, style = self.get_data(element, ranges, style)
        edge_mapping = {
            k: v
            for k, v in mapping[self.edge_glyph].items() if 'color' not in k
        }
        self.handles['previous_id'] = element._plot_id

        properties = {}
        mappings = {}
        for key in list(mapping):
            if not any(glyph in key
                       for glyph in ('scatter_1', self.edge_glyph)):
                continue
            source = self._init_datasource(data.pop(key, {}))
            self.handles[key + '_source'] = source
            glyph_props = self._glyph_properties(plot, element, source, ranges,
                                                 style)
            properties.update(glyph_props)
            mappings.update(mapping.pop(key, {}))
        properties = {
            p: v
            for p, v in properties.items() if p not in ('legend', 'source')
        }
        properties.update(mappings)

        layout = data.pop('layout', {})
        if data and mapping:
            CompositeElementPlot._init_glyphs(self, plot, element, ranges,
                                              source, data, mapping, style)

        # Define static layout
        layout = StaticLayoutProvider(graph_layout=layout)
        node_source = self.handles['scatter_1_source']
        edge_source = self.handles[self.edge_glyph + '_source']
        renderer = plot.graph(node_source, edge_source, layout, **properties)

        # Initialize GraphRenderer
        if self.selection_policy == 'nodes':
            renderer.selection_policy = NodesAndLinkedEdges()
        elif self.selection_policy == 'edges':
            renderer.selection_policy = EdgesAndLinkedNodes()
        else:
            renderer.selection_policy = None

        if self.inspection_policy == 'nodes':
            renderer.inspection_policy = NodesAndLinkedEdges()
        elif self.inspection_policy == 'edges':
            renderer.inspection_policy = EdgesAndLinkedNodes()
        else:
            renderer.inspection_policy = None

        self.handles['layout_source'] = layout
        self.handles['glyph_renderer'] = renderer
        self.handles['scatter_1_glyph_renderer'] = renderer.node_renderer
        self.handles[self.edge_glyph +
                     '_glyph_renderer'] = renderer.edge_renderer
        self.handles['scatter_1_glyph'] = renderer.node_renderer.glyph
        if self.filled or self.bezier:
            glyph_model = Patches if self.filled else Bezier
            allowed_properties = glyph_model.properties()
            for glyph_type in ('', 'selection_', 'nonselection_', 'hover_',
                               'muted_'):
                glyph = getattr(renderer.edge_renderer, glyph_type + 'glyph',
                                None)
                if glyph is None:
                    continue
                props = self._process_properties(self.edge_glyph, properties,
                                                 mappings)
                filtered = self._filter_properties(props, glyph_type,
                                                   allowed_properties)
                new_glyph = glyph_model(**dict(filtered, **edge_mapping))
                setattr(renderer.edge_renderer, glyph_type + 'glyph',
                        new_glyph)
        self.handles[self.edge_glyph + '_glyph'] = renderer.edge_renderer.glyph
        if 'hover' in self.handles:
            self.handles['hover'].renderers.append(renderer)
Beispiel #5
0

def setup_labels(graph):
    label_source = ColumnDataSource(data=dict(
        # x=[pos['x'] for pos in get_positions()],
        # y=[pos['y'] for pos in get_positions()],
        x=x,
        y=y,
        values=get_values()))

    labels = LabelSet(x='x',
                      y='y',
                      text='values',
                      level='overlay',
                      text_align='center',
                      text_baseline='middle',
                      source=label_source,
                      render_mode='canvas')

    return labels


graph_layout = dict(zip(node_indices, zip(x, y)))
graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

plot.renderers.append(graph)
plot.add_layout(setup_labels(graph))

output_file('graph.html')
show(plot)
Beispiel #6
0
    def draw(self):
        graph = self.graph

        N = len(graph.vertices)
        node_indices = list(graph.vertices.keys())

        plot = figure(title="Graph Layout Demonstration",
                      x_range=(-7, 7),
                      y_range=(-7, 7),
                      tools="",
                      toolbar_location=None)

        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        # node_colors = ['red'] * N
        # graph.node_renderer.data_source.add(node_colors, 'color')
        graph_renderer.node_renderer.glyph = Circle(radius=0.5,
                                                    line_width=5,
                                                    line_color="yellow",
                                                    fill_color="red")
        edge_start = []
        edge_end = []

        # O(E), where E is the total number of edges
        for vertex_id in node_indices:
            for v in graph.vertices[vertex_id].edges:
                edge_start.append(vertex_id)
                edge_end.append(v)

        graph_renderer.edge_renderer.data_source.data = dict(start=edge_start,
                                                             end=edge_end)

        ### start of layout code
        # circ = [i*2*math.pi/8 for i in node_indices]
        # x = [math.cos(i) for i in circ]
        # y = [math.sin(i) for i in circ]
        x = []
        y = []
        for vertex_id in node_indices:
            vertex = graph.vertices[vertex_id]
            x.append(vertex.x)
            y.append(vertex.y)

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_renderer)

        labelSource = ColumnDataSource(data=dict(
            x=x, y=y, names=[vertex_id for vertex_id in graph.vertices]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          text_color="white",
                          source=labelSource,
                          render_mode='canvas')

        plot.add_layout(labels)

        output_file('graph.html')
        show(plot)
Beispiel #7
0
network.edge_renderer.data_source.data = dict(start=[1]*total_nodes, end=node_points)

#Render your network in 2-D space

node_circumference = [node*2*math.pi/10 for node in node_points]

x = [math.cos(circum) for circum in node_circumference]

y = [math.sin(circum) for circum in node_circumference]

network_layout = dict(zip(node_points, zip(x, y)))

#Output the network

network.layout_provider = StaticLayoutProvider(graph_layout=network_layout)

plot.renderers.append(network)

output_file('network.html')

show(plot)

---------------------------------------------------------------------------------------------------------

#Network with explicit paths

#Import the required packages

import math
from bokeh.io import show, output_file
Beispiel #8
0
    def show_flow_from_outside_to_buffers_to_tasks(self):
        from bokeh.io import output_file, show
        from bokeh.models import GraphRenderer, Oval, StaticLayoutProvider, ColumnDataSource, LabelSet, Arrow, OpenHead
        from bokeh.plotting import figure
        from bokeh.palettes import Plasma256
        # vector alpha >0 , vector a can be any value
        # a is input/output coming from outside
        # alpha is initial value in buffer
        # matrix G connected buffers and tasks
        # in matrix G , flow between a task and multiple buffers
        # a to buffer to task

        number_of_io_nodes = len(self.a)
        number_of_buffers = self.K
        number_of_tasks = len(self.H[0])
        index_array_of_io = list(range(1, number_of_io_nodes + 1))
        index_array_of_buffers = list(
            range(number_of_io_nodes + 1,
                  number_of_io_nodes + number_of_buffers + 1))
        index_array_of_tasks = list(
            range(number_of_io_nodes + number_of_buffers + 1,
                  number_of_io_nodes + number_of_buffers + number_of_tasks +
                  1))

        node_indices = np.concatenate(
            (index_array_of_io, index_array_of_buffers, index_array_of_tasks),
            axis=None).tolist()
        node_x_location = np.concatenate(
            (index_array_of_io, list(range(1,
                                           len(index_array_of_buffers) + 1)),
             list(range(1,
                        len(index_array_of_tasks) + 1))),
            axis=None).tolist()
        node_y_location = np.concatenate(
            (np.full(number_of_io_nodes, 7), np.full(
                number_of_buffers, 5), np.full(number_of_tasks, 3)),
            axis=None).tolist()

        max_x_range = max(number_of_io_nodes, number_of_buffers,
                          number_of_tasks) + 1

        plot = figure(title='Flow from outside to buffers to tasks',
                      x_range=(0, max_x_range),
                      y_range=(0, 9),
                      tools='',
                      toolbar_location=None)

        graph = GraphRenderer()

        graph.node_renderer.data_source.add(node_indices, 'index')
        graph.node_renderer.data_source.add(Plasma256[:len(node_indices)],
                                            'color')
        graph.node_renderer.glyph = Oval(height=0, width=0, fill_color='color')

        start = index_array_of_io
        end = index_array_of_buffers

        network_graph_buffer_task_hash = {}

        for buffer_index in range(number_of_buffers):
            network_graph_buffer_task_hash[buffer_index + 1] = np.sum(
                self.G[buffer_index, :])

        graph.edge_renderer.data_source.data = dict(start=start, end=end)

        x = node_x_location
        y = node_y_location

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

        plot.renderers.append(graph)

        x_io = list(range(1, number_of_io_nodes + 1))
        y_io = np.full(number_of_io_nodes, 7)
        plot.triangle(x_io,
                      y_io,
                      size=30,
                      color=getLargePalette(number_of_io_nodes, Plasma256),
                      alpha=0.5,
                      line_width=2)

        x_buffers = list(range(1, number_of_buffers + 1))
        y_buffers = np.full(number_of_buffers, 5)
        plot.rect(x_buffers,
                  y_buffers,
                  color=getLargePalette(number_of_buffers, Plasma256),
                  alpha=0.5,
                  width=0.5,
                  height=0.5)

        x_tasks = list(range(1, number_of_tasks + 1))
        y_tasks = np.full(number_of_tasks, 3)
        plot.circle(x_tasks,
                    y_tasks,
                    size=30,
                    color=getLargePalette(number_of_tasks, Plasma256),
                    alpha=0.5)

        for i in range(number_of_buffers):
            for j in range(number_of_tasks):
                if self.G[i, j] > 0:
                    x_start_node = x_buffers[i]
                    y_start_node = y_buffers[i]
                    x_end_node = x_tasks[j]
                    y_end_node = y_tasks[j]
                elif self.G[i, j] < 0:
                    x_start_node = x_tasks[j]
                    y_start_node = y_tasks[j]
                    x_end_node = x_buffers[i]
                    y_end_node = y_buffers[i]
                plot.add_layout(
                    Arrow(end=OpenHead(),
                          x_start=x_start_node,
                          y_start=y_start_node,
                          x_end=x_end_node,
                          y_end=y_end_node))

        text_label_values = np.round(
            np.multiply(
                np.round(list(network_graph_buffer_task_hash.values()), 2),
                100)).tolist()
        text_label_values = [
            str(int(capacity)) + '%' for capacity in text_label_values
        ]

        source = ColumnDataSource(
            data=dict(x=list(network_graph_buffer_task_hash.keys()),
                      y=np.full(number_of_buffers, 4.8),
                      values=text_label_values))
        capacityLabels = LabelSet(x='x',
                                  y='y',
                                  text='values',
                                  level='glyph',
                                  x_offset=-8,
                                  y_offset=10,
                                  source=source,
                                  render_mode='canvas',
                                  text_font_size="10pt")

        plot.add_layout(capacityLabels)

        source = ColumnDataSource(
            data=dict(x=[
                max_x_range / 2 - 0.5, max_x_range / 2 - 0.5, max_x_range / 2 -
                0.5
            ],
                      y=[2.5, 5.5, 7.5],
                      values=['tasks', 'buffers', 'outside sources']))

        typeLabel = LabelSet(x='x',
                             y='y',
                             text='values',
                             level='glyph',
                             x_offset=0,
                             y_offset=0,
                             source=source,
                             render_mode='canvas',
                             text_font_size="10pt")
        plot.add_layout(typeLabel)

        output_file('graph.html')
        show(plot)

        return None
Beispiel #9
0
def player_plot():
    plot = figure(plot_height=500,
                  plot_width=800,
                  tools="save,tap",
                  x_range=[0, 100],
                  y_range=[0, 100],
                  toolbar_location="below")
    plot.image_url(url=["myapp/static/images/base.png"],
                   x=0,
                   y=0,
                   w=100,
                   h=100,
                   anchor="bottom_left")

    lower = np.round(range_slider.value[0])
    higher = np.round(range_slider.value[1])

    filter_data = final_data[(final_data['Game_Time_Start'] >= lower)
                             & (final_data['Game_Time_Start'] <= higher)]
    size = filter_data.groupby(['From', 'To']).size().reset_index(name="Freq")
    grouped = filter_data.groupby(['To'])[['Start_x',
                                           'Start_y']].mean().reset_index()

    G = nx.DiGraph()

    for index, row in grouped.iterrows():
        G.add_node(row['To'], pos=row[['Start_x', 'Start_y']])

    for index, row in size.iterrows():
        G.add_edge(row['From'], row['To'], weight=row['Freq'])

    fixed_pos = grouped.set_index('To').T.to_dict('list')
    fixed_nodes = fixed_pos.keys()
    pos = nx.get_node_attributes(G, 'pos')
    edges = G.edges()
    weights = [G[u][v]['weight'] for u, v in edges]

    graph = from_networkx(G, nx.spring_layout)
    fixed_layout_provider = StaticLayoutProvider(graph_layout=pos)
    graph.layout_provider = fixed_layout_provider

    graph.node_renderer.glyph = Circle(size=20, fill_color='orangered')
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = None
    plot.axis.visible = False
    graph.edge_renderer.data_source.data["line_width"] = [
        G.get_edge_data(a, b)['weight'] for a, b in G.edges()
    ]
    graph.edge_renderer.glyph.line_width = {'field': 'line_width'}

    plot.renderers.append(graph)
    pos_values = np.array(fixed_pos.values())

    coordinates = pd.DataFrame(pos_values, columns=['x', 'y'])
    coordinates['player'] = fixed_pos.keys()
    source = ColumnDataSource(
        data=dict(x=coordinates.x, y=coordinates.y, player=coordinates.player))
    labels = LabelSet(x='x',
                      y='y',
                      text='player',
                      source=source,
                      x_offset=-45,
                      y_offset=-25,
                      text_color='black',
                      render_mode='canvas',
                      text_font_size='10pt')
    plot.renderers.append(labels)
    return plot
Beispiel #10
0
    def draw(self):
        myGraph = self.graph
        N = len(myGraph.vertices)
        # node_indices = list(myGraph.vertices.keys())

        plot = figure(title="Graph Layout Demonstration",
                      x_range=(-7, 7),
                      y_range=(-7, 7),
                      tools="",
                      toolbar_location=None)

        graph = GraphRenderer()

        print("BFT", myGraph.BFT(myGraph.vertices[0].id))
        connected = myGraph.connected_components()
        node_indices = connected
        print("NI", node_indices)
        # graph.node_renderer.data_source.add(range(N), 'index')
        graph.node_renderer.data_source.add(
            [vertex for vertex in list(self.graph.vertices.keys())], 'index')
        hex_keys = [
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
            'd', 'e', 'f'
        ]
        # print(random_color)
        component_colors = []
        for v in myGraph.vertices:
            # print(myGraph.vertices[v].color)
            component_colors.append(f"#{''.join(sample(hex_keys, 6))}")
            # myGraph.vertices[v].color = component_colors[myGraph.vertices[v].component]
        vertex_colors = []
        for vertex in myGraph.vertices:
            vertex_colors.append(
                component_colors[myGraph.vertices[vertex].component])
        print(vertex_colors)
        graph.node_renderer.data_source.add(vertex_colors, 'color')
        graph.node_renderer.glyph = Circle(radius=0.5, fill_color='color')

        edge_start = []
        edge_end = []

        for vertex_id in range(N):
            for v in myGraph.vertices[vertex_id].edges:
                edge_start.append(vertex_id)
                edge_end.append(v)

        graph.edge_renderer.data_source.data = dict(start=edge_start,
                                                    end=edge_end)

        ### start of layout code
        # circ = [i*2*math.pi/8 for i in node_indices]
        # x = [math.cos(i) for i in circ]
        # y = [math.sin(i) for i in circ]
        x = []
        y = []
        for vertex_id in range(N):
            vertex = myGraph.vertices[vertex_id]
            x.append(vertex.x)
            y.append(vertex.y)
        graph_layout = dict(zip(range(N), zip(x, y)))
        graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

        ### Draw quadratic bezier paths
        # def bezier(start, end, control, steps):
        #     return [(1-s)**2*start + 2*(1-s)*s*control + s**2*end for s in steps]

        # xs, ys = [], []
        # sx, sy = graph_layout[0]
        # steps = [i/100. for i in range(100)]
        # for node_index in node_indices:
        #     ex, ey = graph_layout[node_index]
        #     xs.append(bezier(sx, ex, 0, steps))
        #     ys.append(bezier(sy, ey, 0, steps))
        # graph.edge_renderer.data_source.data['xs'] = xs
        # graph.edge_renderer.data_source.data['ys'] = ys
        plot.renderers.append(graph)

        labelSource = ColumnDataSource(data=dict(
            x=x, y=y, names=[vertex_id for vertex_id in myGraph.vertices]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          source=labelSource,
                          render_mode='canvas')

        plot.add_layout(labels)

        output_file("graph.html")
        show(plot)


# graph = Graph()
# graph.add_vertex(0)
# graph.add_vertex(1)
# graph.add_vertex(2)
# graph.add_vertex(3)

# graph.add_edge(0, 1)
# graph.add_edge(0, 3)

# bokehGraph = BokehGraph(graph)
# bokehGraph.draw()
Beispiel #11
0
    def show_task_capacity_per_server(self):
        from bokeh.io import output_file, show
        from bokeh.models import GraphRenderer, Oval, StaticLayoutProvider, ColumnDataSource, LabelSet
        from bokeh.plotting import figure
        from bokeh.palettes import Category20c, Category20
        # we have 12 kinds of tasks (number of columns in H) and 4 time_slots (number of rows in H)
        number_of_servers = len(self.H)
        tasks = ['task ' + str(i) for i in range(1, len(self.H[0]) + 1)]

        index_array_of_tasks = list(range(1, len(tasks) + 1))
        index_array_of_servers = list(
            range(len(tasks) + 1,
                  len(tasks) + number_of_servers + 1))

        number_of_tasks = len(tasks)

        node_indices = np.concatenate(
            (index_array_of_tasks, index_array_of_servers),
            axis=None).tolist()
        node_x_location = np.concatenate(
            (index_array_of_tasks,
             list(range(1,
                        len(index_array_of_servers) + 1))),
            axis=None).tolist()
        node_y_location = np.concatenate(
            (np.full(len(index_array_of_tasks),
                     5), np.full(len(index_array_of_servers), 3)),
            axis=None).tolist()

        plot = figure(title='Task capacity per server',
                      x_range=(0, max(number_of_servers, number_of_tasks) + 1),
                      y_range=(0, 8),
                      tools='',
                      toolbar_location=None)

        graph = GraphRenderer()

        graph.node_renderer.data_source.add(node_indices, 'index')
        graph.node_renderer.data_source.add(Category20c[len(node_indices)],
                                            'color')
        graph.node_renderer.glyph = Oval(height=0, width=0, fill_color='color')

        network_graph_tasks_indices = []
        network_graph_server_indices = []
        network_graph_tasks_server_hash = {}

        for k in range(number_of_servers):  # servers
            for j in range(number_of_tasks):  # tasks
                if self.H[k, j] > 0:
                    network_graph_tasks_indices.append(j + 1)
                    network_graph_server_indices.append(len(tasks) + k + 1)
                    network_graph_tasks_server_hash[j + 1] = self.H[k, j]

        graph.edge_renderer.data_source.data = dict(
            start=list(network_graph_tasks_indices),
            end=list(network_graph_server_indices))

        x = node_x_location
        y = node_y_location

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

        plot.renderers.append(graph)

        x_servers = list(range(1, len(index_array_of_servers) + 1))
        y_servers = np.full(len(index_array_of_servers), 3)
        plot.square(x_servers,
                    y_servers,
                    size=30,
                    color=Category20[number_of_servers],
                    alpha=0.5)

        x_tasks = index_array_of_tasks
        y_tasks = np.full(len(index_array_of_tasks), 5)
        plot.circle(x_tasks,
                    y_tasks,
                    size=30,
                    color=Category20[len(index_array_of_tasks)],
                    alpha=0.5)
        text_label_values = np.round(
            np.multiply(
                np.round(list(network_graph_tasks_server_hash.values()), 2),
                100)).tolist()
        text_label_values = [
            str(int(capacity)) + '%' for capacity in text_label_values
        ]

        source = ColumnDataSource(
            data=dict(x=list(network_graph_tasks_server_hash.keys()),
                      y=np.full(len(network_graph_tasks_indices), 4.8),
                      values=text_label_values))
        capacityLabels = LabelSet(x='x',
                                  y='y',
                                  text='values',
                                  level='glyph',
                                  x_offset=-8,
                                  y_offset=10,
                                  source=source,
                                  render_mode='canvas',
                                  text_font_size="10pt")

        plot.add_layout(capacityLabels)

        source = ColumnDataSource(
            data=dict(x=[6, 6], y=[2.5, 5.5], values=['servers', 'tasks']))

        typeLabel = LabelSet(x='x',
                             y='y',
                             text='values',
                             level='glyph',
                             x_offset=0,
                             y_offset=0,
                             source=source,
                             render_mode='canvas',
                             text_font_size="10pt")
        plot.add_layout(typeLabel)

        output_file('graph.html')
        show(plot)

        return None
Beispiel #12
0
    def draw(self):
        graph = self.graph
        N = len(graph.vertices)
        node_indices = list(graph.vertices.keys())

        plot = figure(title='Graph Layout Demonstration', x_range=(-7,7), y_range=(-7,7),
                    tools='', toolbar_location=None)

        graph_renderer = GraphRenderer()

        edge_start = []
        edge_end = []

        for vertex in node_indices:
            for edge in graph.vertices[vertex].edges:
                edge_start.append(vertex)
                edge_end.append(edge)

        print('edge start', edge_start)
        print('edge end', edge_end)

        graph_renderer.edge_renderer.data_source.data = dict(
            start=edge_start,
            end=edge_end
            )

 
        x = []
        y = []
        ### start of layout code
        for vertex_id in node_indices:
            vertex = graph.vertices[vertex_id]
            x.append(vertex.x)
            y.append(vertex.y)

        source = ColumnDataSource(
            data=dict(
                x = x,
                y = y,
                names = node_indices
            )
        )


        color_mapper = [''] * len(node_indices)

        for index, node in enumerate(node_indices):
            print('color mapper', color_mapper)
            for edge in edge_start:
                if node == edge:
                    print('equals')
                    color_mapper[index] = 'red'

        for index, color in enumerate(color_mapper):
            if color == '':
                color_mapper[index] = 'blue'


        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        graph_renderer.node_renderer.data_source.add(color_mapper, 'color')
        graph_renderer.node_renderer.glyph = Circle(radius=.40, fill_color='color')
        
        graph_renderer_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=graph_renderer_layout)

        labels= LabelSet(
            x = 'x', 
            y = 'y', 
            text='names', 
            level='glyph',
            x_offset = -4,
            y_offset = -8,
            source = source,
            render_mode = 'canvas' 
        )

        plot.renderers.append(graph_renderer)
        plot.add_layout(labels)

        output_file('graph.html')
        show(plot)
Beispiel #13
0
def stream_update(x, vals):

    global f0
    
    nsc = vals["nescience"]
    mis = vals["miscoding"]
    sur = vals["surfeit"]
    ina = vals["inaccuracy"]
    scr = vals["score"]
    
    source_nsc.stream(dict(x=[x], y=[nsc]), rollover=100)
    source_mis.stream(dict(x=[x], y=[mis]), rollover=100)
    source_sur.stream(dict(x=[x], y=[sur]), rollover=100)
    source_ina.stream(dict(x=[x], y=[ina]), rollover=100)
    source_scr.stream(dict(x=[x], y=[scr]), rollover=100)

    # Display neural network
     
    canvas_size = 1
    top    = .9 * canvas_size
    bottom = .1 * canvas_size
    left   = .1 * canvas_size
    right  = .9 * canvas_size

    layer_sizes = vals["layer_sizes"]
    N = np.sum(layer_sizes)

    v_spacing = (top - bottom)/float(max(layer_sizes))
    h_spacing = (right - left)/float(len(layer_sizes) - 1)

    node_indices = list(range(N))

    graph = GraphRenderer()

    graph.node_renderer.data_source.add(node_indices, 'index')

    size = int(v_spacing * 300)
    graph.node_renderer.glyph = Circle(size=size, fill_color='white')

    # Plot edges
    
    start = list()
    end  = list()

    count = 0
    for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
           
        for m in np.arange(layer_size_a):
            for o in np.arange(layer_size_b):
                start.append(count + m)
                end.append(count + layer_size_a + o)
    
        count = count + layer_size_a

    graph.edge_renderer.data_source.data = dict(start=start, end=end)
             
    # Nodes

    x = list()
    y = list()

    for n, layer_size in enumerate(layer_sizes):
    
        layer_top = v_spacing * (layer_size - 1)/2. + (top + bottom)/2.
        
        for m in np.arange(layer_size):

            x.append(n * h_spacing + left)
            y.append(layer_top - m * v_spacing)

    graph_layout = dict(zip(node_indices, zip(x, y)))
    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

    if len(f0.renderers) != 0:
        f0.renderers.pop()
        
    f0.renderers.append(graph) 
Beispiel #14
0
    def draw(self):
        graph = self.graph
        cc = self.cc

        N = len(graph.vertices)
        n = len(cc)

        if self.connected == False:
            graph_colors = sample(Category20[20], N)
        else:
            colors_dict = {}
            colors = list(sample(Category20[20], n))
            for arr in cc:
                color = colors.pop()
                for num in arr:
                    colors_dict[num] = color
            graph_colors = []
            for i in range(N):
                graph_colors.append(colors_dict[i])

            print(f"\nConnected Components: {cc}")

        node_indices = list(graph.vertices.keys())

        plot = figure(title="Bokeh Graph",
                      x_range=(-12, 12),
                      y_range=(-12, 12),
                      tools="",
                      toolbar_location=None)

        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        graph_renderer.node_renderer.data_source.add(graph_colors, 'color')
        graph_renderer.node_renderer.glyph = Circle(radius=0.4,
                                                    fill_color="color")

        edge_start = []
        edge_end = []

        for vertex_id in node_indices:
            for v in graph.vertices[vertex_id].edges:
                edge_start.append(vertex_id)
                edge_end.append(v)

        graph_renderer.edge_renderer.data_source.data = dict(start=edge_start,
                                                             end=edge_end)

        ### start of layout code
        x = []
        y = []
        for vertex_id in node_indices:
            vertex = graph.vertices[vertex_id]
            x.append(vertex.x)
            y.append(vertex.y)

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_renderer)

        labelSource = ColumnDataSource(data=dict(
            x=x, y=y, names=[vertex_id for vertex_id in graph.vertices]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          source=labelSource,
                          render_mode='canvas')

        plot.add_layout(labels)

        output_file('graph.html')
        show(plot)
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)

    x = ['1','2','3','4','5']
    y = [0,0,0,0,0]

    s2 = ColumnDataSource(data=dict(x=x, y=y))

    hplot = figure(title="Rating by user", y_axis_label='% of Ratings Given', x_axis_label="Ratings", toolbar_location=None, tools="",
                x_range=['1','2','3','4','5'], y_range=(0, 50), plot_width=250, plot_height=250)
    hplot.vbar(x='x', top='y', source=s2, width=1, line_color="#ffffff")
    hplot.outline_line_alpha = 0
    hplot.yaxis.axis_line_color = "#a7a7a7"
    hplot.yaxis.major_tick_line_color = "#a7a7a7"
    hplot.yaxis.minor_tick_line_color = None
    hplot.ygrid.grid_line_color = None
    hplot.xgrid.grid_line_color = None
    hplot.xaxis.axis_line_color = "#a7a7a7"
    hplot.xaxis.minor_tick_line_color = None
    hplot.xaxis.major_tick_line_color = "#a7a7a7"


    # callback = CustomJS(args=dict(source=graph.node_renderer.data_source), code =
    # """
    # console.log(cb_obj)
    # var inds = cb_data.source.selected['1d'].indices
    # window.alert(inds)
    # """)
    true_source = ColumnDataSource(data=dict(x=[0,1,10,35,10,0,5,25,8,3,3,4,10,7,1]))

    callback = CustomJS(args=dict(s1=graph.node_renderer.data_source,s2=s2, ts=true_source), code= """
    var inds = cb_data.source.selected['1d'].indices // .source is an on object of cb_data
    //window.alert(inds)
    var data = s2.data
    var tsdata = ts.data
    var ynew = tsdata['x']
    data['y'] = []
    if (inds<150){
        for (var i = 0; i < 5; i++) {
            data['y'].push(ynew[i+5])
        }
    } else if (inds <300){
        for (var i = 0; i < 5; i++) {
            data['y'].push(ynew[i])
        }
    } else {
        for (var i = 0; i < 5; i++) {
            data['y'].push(ynew[i+10])
        }
    }

    s2.change.emit();

    """)


    # 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
    plot.add_tools(TapTool(callback=callback))

    return row(plot,hplot)
Beispiel #16
0
    def show(self):
        graph = self.graph
        node_indices = list(self.graph.vertices)
        N = len(node_indices)
        # print(node_indices)
        plot = figure(title='Graph Layout Demonstration',
                      x_range=(-1.1, 15.1),
                      y_range=(-1.1, 15.1),
                      tools='',
                      toolbar_location=None)

        graph_renderer = GraphRenderer()

        colors = Viridis256[0:N]
        # print(colors)

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        graph_renderer.node_renderer.data_source.add(colors, 'color')
        graph_renderer.node_renderer.glyph = Circle(radius=.2,
                                                    fill_color='color')

        start_indices = []
        end_indices = []

        for vertex_id in graph.vertices:
            for edge_end in graph.vertices[vertex_id].edges:
                start_indices.append(vertex_id)
                end_indices.append(edge_end)

        graph_renderer.edge_renderer.data_source.data = dict(
            start=start_indices, end=end_indices)

        # start of layout code
        # circ = [int(v*2*math.pi/8) for v in self.graph.vertices]
        linear = [int(v * 2 * math.pi / 8) for v in self.graph.vertices]
        # x = [math.cos(i) for i in circ]
        # y = [math.sin(i) for i in circ]

        x = [graph.vertices[vertex_id].x for vertex_id in graph.vertices]
        y = [graph.vertices[vertex_id].y for vertex_id in graph.vertices]

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_renderer)

        labelSource = ColumnDataSource(
            data=dict(x=x,
                      y=y,
                      names=[
                          graph.vertices[vertex_id].value
                          for vertex_id in graph.vertices
                      ]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          source=labelSource,
                          render_mode='canvas')

        plot.add_layout(labels)

        output_file('graph.html')
        show(plot)


# graph = Graph()
# bokeh = BokehGraph(graph)
# bokeh.graph.add_vertex('0')
# bokeh.graph.add_vertex('1')
# bokeh.graph.add_vertex('2')
# bokeh.graph.add_vertex('3')
# bokeh.graph.add_edge('0', '1')
# bokeh.graph.add_edge('0', '3')
# bokeh.graph.add_edge('2', '3')
# bokeh.graph.add_vertex('4')
# bokeh.graph.add_edge('2', '4')
# bokeh.graph.add_edge('4', '3')

# bokeh.show()
def interactiveG(G):
    from bokeh.models.graphs import NodesAndLinkedEdges, from_networkx
    from bokeh.models import Circle, HoverTool, MultiLine, Plot, Range1d, StaticLayoutProvider
    from bokeh.plotting import figure, output_file, show, ColumnDataSource
    from bokeh.io import output_notebook, show
    output_notebook()
    # We could use figure here but don't want all the axes and titles
    #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))

    output_file("PHMI_network")
    source = ColumnDataSource(data=dict(
        x=locations[0].tolist(),
        #x=[idx for idx in range(len(PHMIList))],
        #y=locations[1].tolist(),
        y=PHMIList,
        #desc=[str(i) for i in PHMIList],
        #PHMI_value=PHMI_dic[0][0].tolist(),
    ))
    TOOLTIPS = [
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        #("desc", "@desc"),
        #("PHMI", "$PHMI_value"),
    ]

    plot = figure(x_range=Range1d(-1.1, 1.1),
                  y_range=Range1d(-1.1, 1.1),
                  plot_width=2200,
                  plot_height=500,
                  tooltips=TOOLTIPS,
                  title="PHMI_network")

    #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()}
    graph = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))
    #plot.renderers.append(graph)

    fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position)
    graph.layout_provider = fixed_layout_provider
    plot.renderers.append(graph)

    # Blue circles for nodes, and light grey lines for edges
    graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba')
    graph.edge_renderer.glyph = MultiLine(line_color="#cccccc",
                                          line_alpha=0.8,
                                          line_width=2)

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

    # When we hover over nodes, highlight adjecent edges too
    graph.inspection_policy = NodesAndLinkedEdges()

    plot.add_tools(HoverTool(tooltips=None))

    colors = (
        'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige',
        'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown',
        'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral',
        'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue',
        'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey',
        'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange',
        'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue',
        'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet',
        'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue',
        'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
        'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow',
        'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki',
        'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue',
        'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray',
        'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen',
        'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue',
        'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
        'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
        'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
        'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
        'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
        'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
        'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
        'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
        'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
        'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
        'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
        'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
        'whitesmoke', 'yellow', 'yellowgreen')
    ScalePhmi = math.pow(10, 1)
    i = 0
    for val, idx in zip(phmi_breakPtsNeg, plot_x):
        plot.line(idx, np.array(val) * ScalePhmi, line_color=colors[i])
        i += 1

    show(plot)
Beispiel #18
0
def generate_bokeh_graph():

    N = 8
    node_indices = list(range(N))

    plot = figure(title="Graph Layout Demonstration",
                  x_range=(-1.1, 1.1),
                  y_range=(-1.1, 1.1),
                  tools="",
                  toolbar_location=None)

    graph = GraphRenderer()

    graph.node_renderer.data_source.add(node_indices, 'index')
    graph.node_renderer.data_source.add(Spectral8, 'color')
    graph.node_renderer.glyph = Oval(height=0.1, width=0.2, fill_color="color")

    graph.edge_renderer.data_source.data = dict(start=[0] * N,
                                                end=node_indices)

    ### start of layout code
    circ = [i * 2 * math.pi / 8 for i in node_indices]
    x = [math.cos(i) for i in circ]
    y = [math.sin(i) for i in circ]
    graph_layout = dict(zip(node_indices, zip(x, y)))
    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

    ### Draw quadratic bezier paths
    def bezier(start, end, control, steps):
        return [(1 - s)**2 * start + 2 * (1 - s) * s * control + s**2 * end
                for s in steps]

    xs, ys = [], []
    sx, sy = graph_layout[0]
    steps = [i / 100. for i in range(100)]
    for node_index in node_indices:
        ex, ey = graph_layout[node_index]
        xs.append(bezier(sx, ex, 0, steps))
        ys.append(bezier(sy, ey, 0, steps))
    graph.edge_renderer.data_source.data['xs'] = xs
    graph.edge_renderer.data_source.data['ys'] = ys

    plot.renderers.append(graph)

    output_file("graph.html")
    show(plot)


# generate_bokeh_graph()
#
# u = Digraph('digraph', file_path='digraph.gv',
#             node_attr={'color': 'lightblue2', 'style': 'filled'})
# u.attr(size='6,6')
#
# u.edge('5th Edition', '6th Edition', label='n')
# u.edge('5th Edition', 'PWB 1.0',label='n')
# u.edge('6th Edition', 'LSX',label='n')
# u.edge('6th Edition', '1 BSD')
# u.edge('6th Edition', 'Mini Unix')
# u.edge('6th Edition', 'Wollongong')
# u.edge('6th Edition', 'Interdata')
# u.edge('Interdata', 'Unix/TS 3.0')
# u.edge('Interdata', 'PWB 2.0')
# u.edge('Interdata', '7th Edition')
# u.edge('7th Edition', '8th Edition')
# u.edge('7th Edition', '32V')
# u.edge('7th Edition', 'V7M')
# u.edge('7th Edition', 'Ultrix-11')
# u.view()

#https://stackoverflow.com/questions/51038073/flask-dynamic-graphviz-and-svg-example
# You can use svg just like this:
#
# {{ chart_output|safe }}
# and also, you can use png format:
#
# @app.route('/')
# def svgtest():
#     chart_data = Graph()
#
#     chart_data.node('H', 'Hello')
#     chart_data.node('W', 'World')
#     chart_data.edge('H', 'W')
#
#
#     chart_output = chart_data.pipe(format='png')
#     chart_output = base64.b64encode(chart_output).decode('utf-8')
#
#     return render_template('svgtest.html', chart_output=chart_output)
# and the html like this:
#
# <img src="data:image/png;base64,{{chart_output|safe}}" />
Beispiel #19
0
    def draw(self):
        graph = self.graph

        N = len(graph.vertices)
        node_indices = list(graph.vertices.keys())

        plot = figure(title="Graph Demonstration",
                      x_range=(-7, 7),
                      y_range=(-7, 7),
                      tools="",
                      toolbar_location=None)

        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        # node_colors = ['blue'] * N
        # graph_renderer.node_renderer.data_source.add(node_colors, 'color')
        graph_renderer.node_renderer.glyph = Circle(radius=0.5,
                                                    fill_color='blue')

        edge_start = []
        edge_end = []

        for vertex_id in node_indices:
            for v in graph.vertices[vertex_id].edges:
                edge_start.append(vertex_id)
                edge_end.append(v)

        graph_renderer.edge_renderer.data_source.data = dict(start=edge_start,
                                                             end=edge_end)

        ### start of layout code
        x = []
        y = []
        for vertex_id in node_indices:
            vertex = graph.vertices[vertex_id]
            x.append(vertex.x)
            y.append(vertex.y)

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_renderer)

        labelSource = ColumnDataSource(data=dict(
            x=x, y=y, names=[vertex_id for vertex_id in graph.vertices]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          source=labelSource,
                          render_mode='canvas',
                          text_color='white')

        plot.add_layout(labels)

        output_file('test_graph.html')
        show(plot)
Beispiel #20
0
    def build_lay_out(graph_renderer, axis):
        graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=axis)

        return graph_renderer
Beispiel #21
0
def make_figure(nodes, edges, correlation_edges, pos):
  
  # define gplot
  gplot = figure(title=None, x_range=(-2, 2), y_range=(-2, 2), tools="reset,save",
         plot_width=900, plot_height=900, match_aspect=False)

  graph = GraphRenderer()

  # add nodes
  light_node = Ellipse(height=RADIUS, width=RADIUS, fill_color="color", line_color="#000000", line_width=5)
  heavy_node = Ellipse(height=RADIUS, width=RADIUS, fill_color="color", line_color="#000000", line_width=7)
  
  for k in nodes:
    graph.node_renderer.data_source.add(nodes[k], k)
  
  graph.node_renderer.glyph = light_node
  graph.node_renderer.hover_glyph = heavy_node
  graph.node_renderer.selection_glyph = heavy_node
  graph.node_renderer.nonselection_glyph = light_node

  # add directed edges
  graph.edge_renderer.name = "edges"
  
  for k in correlation_edges:
    graph.edge_renderer.data_source.add(correlation_edges[k], k)

  light_edge = MultiLine(line_width="width", line_color="color", line_alpha="alpha")
  heavy_edge = MultiLine(line_width="width", line_color="color", line_alpha=1)
  
  graph.edge_renderer.glyph = light_edge
  graph.edge_renderer.hover_glyph = heavy_edge
  graph.edge_renderer.selection_glyph = light_edge
  graph.edge_renderer.nonselection_glyph = light_edge

  # arrows
  arrow = NormalHead(fill_color="#000000", line_color=None, size=8)
  arrow_source = ColumnDataSource(dict(x_start=[], y_start=[], x_end=[], y_end=[]))
  gplot.add_layout(
    Arrow(
      end=arrow, source=arrow_source,
      x_start="x_start", y_start="y_start", x_end="x_end", y_end="y_end"
    )
  )

  # add labels
  p_ind = np.linspace(0, 1-1/len(pos), len(pos)) * np.pi * 2
  xr = 1.1 * np.cos(p_ind)
  yr = 1.1 * np.sin(p_ind)
  rad = np.arctan2(yr, xr)
  gplot.text(xr, yr, nodes["index"], angle=rad,
    text_font_size="9pt", text_align="left", text_baseline="middle")

  # render
  graph.layout_provider = StaticLayoutProvider(graph_layout=pos)
  graph.inspection_policy = EdgesAndLinkedNodes()
  graph.selection_policy = NodesAndLinkedEdges()

  # widgets
  edges_original = ColumnDataSource(edges)

  slider = Slider(start=0.0, end=1.0, value=0.0, step=0.1, 
    title="absolute correlation coefficient is greater than")

  checkbox = CheckboxButtonGroup(
    labels=EDGE_LABELS, 
    active=[0]
  )

  callback = CustomJS(
    args=dict(
      graph=graph,
      edges_original=edges_original, 
      arrow_source=arrow_source,
      checkbox=checkbox,
      slider=slider
    ), 
    code="""
      var e = graph.edge_renderer.data_source.data;
      var n = graph.node_renderer.data_source.data;
      var a = arrow_source.data;
      var o = edges_original.data;
      var cb = checkbox.active;
      var sv = slider.value;
      var ns = graph.node_renderer.data_source.selected.indices;
      if (ns.length > 0) {
        var nn = n['index'][ns[0]];
        for (var key in o) {
          var vals = [];
          for (var i = 0; i < o['start'].length; ++i) {
            if ((o['start'][i] == nn || o['end'][i] == nn) && (Math.abs(o['r'][i]) > sv) && (cb.indexOf(o['type'][i]) > -1)) {
              vals.push(o[key][i]);
            }
          }
          e[key] = vals;
        }
        a['x_start'].length = 0;
        a['y_start'].length = 0;
        a['x_end'].length = 0;
        a['y_end'].length = 0;
        for (var i = 0; i < o['start'].length; ++i) {
          if ((o['start'][i] == nn || o['end'][i] == nn) && (Math.abs(o['r'][i]) > sv) && (cb.indexOf(o['type'][i]) > -1)) {
            if (o['e_arrow'][i] === 1) {
              var l = o['xs'][i].length;
              a['x_start'].push(o['xs'][i][l - 2]);
              a['y_start'].push(o['ys'][i][l - 2]);
              a['x_end'].push(o['xs'][i][l - 1]);
              a['y_end'].push(o['ys'][i][l - 1]);
            }
            if (o['b_arrow'][i] === 1) {
              a['x_start'].push(o['xs'][i][1]);
              a['y_start'].push(o['ys'][i][1]);
              a['x_end'].push(o['xs'][i][0]);
              a['y_end'].push(o['ys'][i][0]);
            }
          }
        }
      } else {
          for (var key in o) {
          var vals = [];
          for (var i = 0; i < o['start'].length; ++i) {
            if ((Math.abs(o['r'][i]) > sv) && (cb.indexOf(o['type'][i]) > -1)) {
              vals.push(o[key][i]);
            }
          }
          e[key] = vals;
        }
        a['x_start'].length = 0;
        a['y_start'].length = 0;
        a['x_end'].length = 0;
        a['y_end'].length = 0;
        for (var i = 0; i < o['start'].length; ++i) {
          if ((Math.abs(o['r'][i]) > sv) && (cb.indexOf(o['type'][i]) > -1)) {
            if (o['e_arrow'][i] === 1) {
              var l = o['xs'][i].length;
              a['x_start'].push(o['xs'][i][l - 2]);
              a['y_start'].push(o['ys'][i][l - 2]);
              a['x_end'].push(o['xs'][i][l - 1]);
              a['y_end'].push(o['ys'][i][l - 1]);
            }
            if (o['b_arrow'][i] === 1) {
              a['x_start'].push(o['xs'][i][1]);
              a['y_start'].push(o['ys'][i][1]);
              a['x_end'].push(o['xs'][i][0]);
              a['y_end'].push(o['ys'][i][0]);
            }
          }
        }
      }
      graph.edge_renderer.data_source.change.emit();
      arrow_source.change.emit();
  """)
  slider.js_on_change("value", callback)
  checkbox.js_on_change("active", callback)
  graph.node_renderer.data_source.selected.js_on_change("indices", callback)
  
  hover = HoverTool(
    tooltips=[
      ("node", "@start"),
      ("node", "@end"),
      ("type", "@type_name"),
      ("pearson", "@r{0.3f}"),
      ("p-value", "@pval"),
    ],
    renderers=[graph]
  )
  
  gplot.background_fill_color = BACKGROUND
  gplot.xgrid.grid_line_color = None
  gplot.ygrid.grid_line_color = None
  gplot.axis.visible = False
  gplot.add_tools(hover, TapTool())
  gplot.toolbar.logo = None
  gplot.toolbar_location = None
  gplot.border_fill_color = None
  gplot.outline_line_color = None
  gplot.renderers.append(graph)
  
  return {
    "gplot": gplot, 
    "widgets": widgetbox(slider, checkbox, width=450)
  }
Beispiel #22
0
    def draw(self):
        graph = self.graph
        N = len(graph.vertices)
        node_indices = list(graph.vertices)

        plot = figure(
            title='Graph Layout Demonstration',
            x_range=(-1.1, 50),
            y_range=(-1.1, 5),
            #   tools='', toolbar_location=None,
            plot_width=1450,
            plot_height=1000)

        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        graph_renderer.node_renderer.data_source.add(
            [graph.vertices[vertex_id].color for vertex_id in graph.vertices],
            'color')
        graph_renderer.node_renderer.glyph = Circle(radius=0.5,
                                                    fill_color='color')

        start_indices = []
        end_indices = []

        for vertex_id in graph.vertices:
            for edge_end in graph.vertices[vertex_id].edges:
                start_indices.append(vertex_id)
                end_indices.append(edge_end)

        graph_renderer.edge_renderer.data_source.data = dict(
            start=start_indices, end=end_indices)

        ### start of layout code
        x = [graph.vertices[vertex_id].x for vertex_id in graph.vertices]
        y = [graph.vertices[vertex_id].y for vertex_id in graph.vertices]

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot.renderers.append(graph_renderer)

        labelSource = ColumnDataSource(
            data=dict(x=x,
                      y=y,
                      names=[
                          graph.vertices[vertex_id].value
                          for vertex_id in graph.vertices
                      ]))
        labels = LabelSet(x='x',
                          y='y',
                          text='names',
                          level='glyph',
                          text_align='center',
                          text_baseline='middle',
                          source=labelSource,
                          render_mode='canvas')

        plot.add_layout(labels)

        output_file('graph.html')
        show(plot)
Beispiel #23
0
    def show(self):
        graph = self.graph
        N = len(self.graph.vertices)
        # node_indices = 4
        node_indices = list(self.graph.vertices.keys())

        plot = figure(title="Mike Kerbleski Graph",
                      x_range=(0, 10.1),
                      y_range=(0, 10.1),
                      tools="",
                      toolbar_location=None)

        graph_renderer = GraphRenderer()

        edge_start = []
        edge_end = []

        # print(node_indices)

        for vertex_id in node_indices:
            for v in graph.vertices[vertex_id].edges:
                edge_start.append(vertex_id)
                edge_end.append(v)

        graph_renderer.edge_renderer.data_source.data = dict(start=edge_start,
                                                             end=edge_end)

        x = []
        y = []

        colors = []
        labels = []
        color1 = "red"
        color2 = "blue"

        for vertex_id in node_indices:
            labels.append('hello')
            if vertex_id in edge_start:
                colors.append(color1)
            else:
                colors.append(color2)

            vertex = graph.vertices[vertex_id]
            x.append(vertex.x)
            y.append(vertex.y)

        graph_renderer.node_renderer.data_source.add(node_indices, 'index')
        graph_renderer.node_renderer.data_source.add(colors, 'color')
        graph_renderer.node_renderer.glyph = Oval(height=0.1,
                                                  width=0.2,
                                                  fill_color="color")

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        ### Draw quadratic bezier paths
        def bezier(start, end, control, steps):
            return [(1 - s)**2 * start + 2 * (1 - s) * s * control + s**2 * end
                    for s in steps]

        plot.renderers.append(graph_renderer)

        output_file("graph.html")
        show(plot)
def plot_data(data_df, connections, year, geoSource_new):

    data_df_countries = data_df  #.drop_duplicates(subset=None, keep='first', inplace=True)
    connections_df = connections

    node_source = ColumnDataSource(
        data_df_countries[["country_id", "Country", "Longitude", "Latitude"]])
    edge_source = ColumnDataSource(connections_df[["start", "end"]])

    node_renderer = GlyphRenderer(data_source=node_source,
                                  glyph=node_glyph,
                                  selection_glyph=node_selection,
                                  nonselection_glyph=node_nonselection)

    ## Create edge_renderer
    edge_renderer = GlyphRenderer(data_source=edge_source,
                                  glyph=edge_glyph,
                                  hover_glyph=edge_hover,
                                  selection_glyph=edge_selection,
                                  nonselection_glyph=edge_nonselection)
    ## Create layout_provider
    graph_layout = dict(
        zip(data_df_countries.country_id.astype(str),
            zip(data_df_countries.Longitude, data_df_countries.Latitude)))
    layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

    ## Create graph renderer
    graph = GraphRenderer(edge_renderer=edge_renderer,
                          node_renderer=node_renderer,
                          layout_provider=layout_provider,
                          inspection_policy=NodesAndLinkedEdges(),
                          selection_policy=NodesAndLinkedEdges())

    plot = Plot(x_range=Range1d(-150, 150),
                y_range=Range1d(15, 75),
                plot_width=800,
                plot_height=600,
                background_fill_color=Set3_12[4],
                background_fill_alpha=0.2)

    plot.title.text = "Human Trafficing Visualization for " + str(year)

    # plot.add_glyph( geoSource_data, Patches(xs='xs', ys='ys', line_color='grey'
    #                      , line_width=.5, fill_color=Set3_12[6], fill_alpha=0.25))

    plot.add_glyph(
        geoSource_new,
        Patches(xs='xs',
                ys='ys',
                line_color='grey',
                line_width=.2,
                fill_color={
                    'field': 'Tier',
                    'transform': mapper2
                },
                fill_alpha=0.25))

    plot.renderers.append(graph)
    plot.add_layout(LinearAxis(axis_label="Latitude"), "below")
    plot.add_layout(LinearAxis(axis_label="Longitude"), "left")

    hover = HoverTool(
        show_arrow=True,  # tooltips=  # [("Country Involved: ", "@Country")],
        tooltips="""
                                <div>
                                    <div>
                                        <span style="font-size: 15px;">Country Information </span>
                                        <span style="font-size: 12px; color: #696;">@Destination_Country </span>
                                    </div>
                                </div>
                                """,
        renderers=[graph])
    hover_no_tooltips = HoverTool(tooltips=None, renderers=[graph])
    box_zoom = BoxZoomTool()

    plot.add_tools(hover, hover_no_tooltips, box_zoom, TapTool(),
                   BoxSelectTool(), ResetTool(), WheelZoomTool())
    plot.toolbar.active_inspect = [hover, hover_no_tooltips]
    plot.toolbar.active_drag = box_zoom
    plot.outline_line_color = "navy"
    plot.outline_line_alpha = 0.3
    plot.outline_line_width = 3
    plot.add_tile(STAMEN_TONER_LABELS)

    return plot
def generateNodeLinkGraph(file):
    #Reading the file
    file = file + '.csv'
    fname = os.path.join(server.config['UPLOAD_FOLDER'], file)
    f = open(fname, 'r')

    #Reading first line
    line1 = f.readline()
    names = line1[1:].split(';')

    # Rename duplicates since there are people with the same name
    seen = {}
    dupes = []

    for index, name in enumerate(names):
        if name not in seen:
            seen[name] = 1
        else:
            if seen[name] == 1:
                dupes.append((index, name))
            seen[name] += 1

    # add 1, 2 etc after the name
    for pair in dupes:
        index = pair[0]
        name = pair[1]
        for i in range(seen[name]):
            names[index] = name + str((i+1))
            #print(names[index])

    # Read csv
    df = pd.read_csv(f, names=names, sep=';')

    # Fix it
    df = df.reset_index(level=1)
    names.append("delete")
    df.columns = names
    del df["delete"]
    df.set_index([df.columns], inplace=True)

    # Get names again for later use
    names = df.columns.tolist()

    # Get 150*150 sub matrix since otherwise the plot is very slow..
    df = df.head(150)[names[0:150]]
    names = df.columns.tolist()

    #Get total amount of nodes
    N = len(names)
    node_indices = list(range(N)) #Create list of numeric node indices

    # Scale for the repeating pattern of the colours
    scale = math.ceil(N / 256)

    #Iterate over dataframe and save non-zero edges
    start = [] #Contains starting node index of each edge
    end = [] #Contains ending node index of each edge
    tolerance = 0.75 #Determine which edges are shown and which are not

    index_count = 0 #Set start node index to 0
    for row in df.itertuples(): #For each row in the dataframe
        index_count += 1 #Increase start node index by 1
        element_count = 0 #(Re)set second node index to 0
        for element in row: #For each element in each row
            element_count += 1 #Increase second node index by 1
            if type(element) == float:
                #if element == 1.0: #Code in case for symmetric matrix, effectively halving running time of this loop
                #    break
                #elif element > tolerance:
                if element > tolerance and not element == 1.0:
                    start.append(index_count) #Add starting node index to the edge starting list
                    end.append(element_count) #Add ending node index to the edge ending list

    #Create the plot with two axes, a title and interaction tools
    #plot = figure(title='Circular Node-Link Diagram', x_range=(0 - (N * 2.1) , N * 2.1), y_range=(0 - (N * 2.1) , N * 2.1),
    #              tools='pan, wheel_zoom, reset', toolbar_location = 'right', frame_height = 400, frame_width = 400, output_backend="webgl")
    plot = Plot(x_range=Range1d(0 - (N * 2.1) , N * 2.1), y_range=Range1d(0 - (N * 2.1) , N * 2.1),
              toolbar_location = 'right', frame_height = 400, frame_width = 400, output_backend="webgl")

    plot.title.text = "Circular Node-Link Diagram"

    plot.add_tools(PanTool(), BoxZoomTool(), ResetTool())

    #Create the graph object
    graph = GraphRenderer()

    #Assign the correct data for the edges
    #graph.edge_renderer.data_source.data = dict(
    #    start = start,
    #    end = end)
    #graph.edge_renderer.glyph = MultiLine(line_color = Viridis256[200])

    #Assign the correct data for the nodes
    graph.node_renderer.data_source.add(node_indices, 'index')
    graph.node_renderer.data_source.add(Viridis256 * scale, 'color')
    graph.node_renderer.glyph = Circle(radius = N * 0.0025, fill_color='color')

    #Start of circular layout code
    circ = [i * 2 * math.pi/N for i in node_indices]
    x = [2 * N * math.cos(i) for i in circ]
    y = [2 * N * math.sin(i) for i in circ]

    #Assign the correct x and y values to all nodes
    graph_layout = dict(zip(node_indices, zip(x, y)))
    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

    #Arrow code test
    for start_index in start:
        start_index -= 1
        for end_index in end:
            end_index -= 1
            plot.add_layout(Arrow(end = NormalHead(fill_color = Viridis256[200], size = N * 0.1), x_start = x[start_index], y_start = y[start_index],
                                  x_end = x[end_index], y_end = y[end_index], line_color = Viridis256[200]))
            end_index += 1
        start_index += 1

    #Show the plot
    plot.renderers.append(graph)
    script, div = components(plot)
    return script, div
Beispiel #26
0
for v in value_list:
    size_list.append(9)
    if v > 10000:
        color_list.append(allcolor[1])
    elif v > 5000:
        color_list.append(allcolor[2])
    elif v > 0:
        color_list.append(allcolor[3])
    else:
        color_list.append(allcolor[1])

for e in G.edges:
    width_list.append(1)

print(mean(value_list))
fixed_layout_provider = StaticLayoutProvider(graph_layout=modified_pos)
graph_renderer.layout_provider = fixed_layout_provider
graph_renderer.node_renderer.glyph = Circle(size='size', fill_color='colors')
graph_renderer.edge_renderer.glyph = MultiLine(line_color="purple",
                                               line_alpha='width',
                                               line_width=1)
x, y = zip(*graph_renderer.layout_provider.graph_layout.values())
graph_renderer.node_renderer.data_source.data['x'] = x
graph_renderer.node_renderer.data_source.data['y'] = y
graph_renderer.node_renderer.data_source.data['colors'] = color_list
graph_renderer.node_renderer.data_source.data['label'] = label_list
graph_renderer.node_renderer.data_source.data['size'] = size_list
graph_renderer.edge_renderer.data_source.data['width'] = width_list

event_radius_dummy_1 = plot.circle(1,
                                   1,
Beispiel #27
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="#A0DF3F")
    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)
    plot.add_tools(TapTool())

    return plot
Beispiel #28
0
    def show(self):
        # color1 = [Viridis256[1]]*len(self.vertices)
        # color2 = Viridis10
        # currentcolor = color1
        colors = []  # [orange, white, ]
        i = random.randint(0, 256)
        for g in self.graphIn.groups:
            colors += [Viridis256[i]] * len(g)
            i = random.randint(0, 256)

        print(colors)
        node_indices = self.vertices
        plot = figure(title='Graph Layout Demonstration',
                      x_range=(-1.1, 1.1),
                      y_range=(-1.1, 1.1),
                      tools='',
                      toolbar_location=None)

        graph = GraphRenderer()
        graph.node_renderer.data_source.add([
            vertex for subgroup in self.graphIn.groups for vertex in subgroup
        ], 'index')  #               [6,7,1,2,3,4,5]
        graph.node_renderer.data_source.add(
            colors, 'color'
        )  #graph.groups = [[6], [7], [1,2,3,4,5]]   [orange, purp, gray, gray, gray, gray, gray]
        graph.node_renderer.glyph = Circle(radius=0.1,
                                           fill_color='color',
                                           name=str(node_indices))

        starts = []
        for k in self.graphIn.vertices.keys():
            starts += [k] * (len(self.graphIn.vertices[k]))
        ends = []
        for k, v in self.graphIn.vertices.items():
            ends += v
        graph.edge_renderer.data_source.data = dict(start=starts, end=ends)

        circ = [
            int(i) * 2 * math.pi / len(self.vertices) for i in node_indices
        ]
        x = [math.cos(i) for i in circ]
        y = [math.sin(i) for i in circ]

        graph_layout = dict(zip(node_indices, zip(x, y)))
        graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

        # setup labels
        data = {'x': x, 'y': y, 'name': node_indices}
        source = ColumnDataSource(data)
        labels = LabelSet(x="x",
                          y="y",
                          text="name",
                          y_offset=-5,
                          text_font_size="12pt",
                          text_color="white",
                          source=source,
                          text_align='center')

        plot.add_layout(labels)
        plot.renderers.append(graph)

        output_file('graph2.html')
        show(plot)
Beispiel #29
0
G_lps3 = nx.from_pandas_edgelist(pd.DataFrame(src_lps3.data))
graph_renderer_lps3 = from_networkx(G_lps3,
                                    nx.circular_layout,
                                    scale=1,
                                    center=(0, 0))

node_indices_lps3 = list(range(p_lps3))
circ = [i * 2 * np.pi / p_lps3 for i in node_indices_lps3]
x = np.array([x_layout(t) for t in circ])
y = np.array([y_layout(t) for t in circ])
scale = np.max([x, y])
x = (x - np.mean(x)) / (scale - np.mean(x))
y = (y - np.mean(y)) / (scale - np.mean(y))

graph_layout = dict(zip(node_indices_lps3, zip(x, y)))
graph_renderer_lps3.layout_provider = StaticLayoutProvider(
    graph_layout=graph_layout)

plot_lps3.renderers.append(graph_renderer_lps3)

controls_lps3 = WidgetBox(p_select_lps3, div_lps3)

# Create a row layout
layout_lps3 = row(controls_lps3, plot_lps3)

# Make a tab with the layout
tab_lps3 = Panel(child=layout_lps3, title='LPS3')

######################################################################
# Paley graph
######################################################################
Beispiel #30
0
    def show(self):
        #Get list of nodes
        nodes = list(self.graph.vertices.keys())

        #Create plot figure
        plot = figure(title='Graph Plot',
                      x_range=(-1.5, 1.5),
                      y_range=(-1.5, 1.5),
                      tools="",
                      toolbar_location=None)

        #create a GraphRenderer Object
        G = GraphRenderer()

        #map nodes to node_renderer and format glyph for nodes
        G.node_renderer.glyph = Circle(radius=0.1, fill_color="fill_color")
        G.node_renderer.data_source.data = dict(index=nodes,
                                                fill_color=['orange'] *
                                                len(nodes))

        #Get start and end list of edges
        edge_starts = []
        edge_ends = []
        for k, v in self.graph.vertices.items():
            edge_starts += [k] * len(v)
            edge_ends += v

        #map data to edge_renderer and format glyph for edges
        G.edge_renderer.glyph = MultiLine(line_color="#cccccc",
                                          line_alpha=0.8,
                                          line_width=2)
        G.edge_renderer.data_source.data = dict(start=edge_starts,
                                                end=edge_ends)

        #add hover effects for nodes and edges
        G.node_renderer.hover_glyph = Circle(radius=0.3)
        G.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4',
                                                line_width=4)

        # When we hover over nodes, highlight adjecent edges too
        G.inspection_policy = NodesAndLinkedEdges()

        #setup layout coordinates
        circ = [i * 2 * math.pi / len(nodes) for i in range(len(nodes))]
        x = [math.cos(i) for i in circ]
        y = [math.sin(i) for i in circ]

        graph_layout = dict(zip(nodes, zip(x, y)))
        G.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

        #setup labels
        data = {'x': x, 'y': y, 'name': nodes}
        source = ColumnDataSource(data)
        labels = LabelSet(x="x",
                          y="y",
                          text="name",
                          y_offset=-5,
                          text_font_size="12pt",
                          text_color="#555555",
                          source=source,
                          text_align='center')

        #add
        plot.renderers.append(G)
        #Add hovering tool
        plot.add_tools(HoverTool(tooltips=None))
        #Add node label
        plot.add_layout(labels)

        #save file to graph.html
        output_file('graph.html')

        #show plot
        show(plot)


# #create graph
# graph = Graph()

# #Add vertexes
# graph.add_vertex('v1')
# graph.add_vertex('v2')
# graph.add_vertex('v3')
# graph.add_vertex('v4')
# graph.add_vertex('v5')
# graph.add_vertex('v6')
# graph.add_vertex('v7')
# graph.add_vertex('v8')
# graph.add_vertex('v9')
# graph.add_vertex('v10')
# graph.add_vertex('v11')
# graph.add_vertex('v12')
# graph.add_vertex('v13')
# graph.add_vertex('v14')

# #add edges
# graph.add_directed_edge('v1', 'v2')
# graph.add_directed_edge('v2', 'v1')
# graph.add_directed_edge('v2', 'v7')
# graph.add_directed_edge('v3', 'v8')
# graph.add_directed_edge('v5', 'v6')
# graph.add_directed_edge('v5', 'v10')
# graph.add_directed_edge('v6', 'v5')
# graph.add_directed_edge('v6', 'v7')
# graph.add_directed_edge('v7', 'v2')
# graph.add_directed_edge('v7', 'v6')
# graph.add_directed_edge('v8', 'v3')
# graph.add_directed_edge('v8', 'v7')
# graph.add_directed_edge('v8', 'v9')
# graph.add_directed_edge('v8', 'v13')
# graph.add_directed_edge('v9', 'v8')
# graph.add_directed_edge('v9', 'v14')
# graph.add_directed_edge('v10', 'v5')
# graph.add_directed_edge('v12', 'v13')
# graph.add_directed_edge('v13', 'v12')
# graph.add_directed_edge('v13', 'v8')
# graph.add_directed_edge('v13', 'v14')
# graph.add_directed_edge('v14', 'v13')
# graph.add_directed_edge('v14', 'v9')

# bokeh_graph = BokehGraph(graph)
# bokeh_graph.show()