示例#1
0
文件: molecule.py 项目: cjforman/pele
    def draw_graph(self, G, node_list=None, edge_colour='k', node_size=15, node_colour='r', graph_type='spring',
                   back_bone=None, side_chains=None, terminators=None):
        # determine nodelist
        if node_list is None:
            node_list = G.nodes()
        # determine labels
        labels = {}
        for l_atom in G.nodes_iter():
            labels[l_atom] = l_atom.symbol

        # draw graphs based on graph_type
        if graph_type == 'circular':
            nx.draw_circular(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'random':
            nx.draw_random(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spectral':
            nx.draw_spectral(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spring':
            nx.draw_spring(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'shell':
            nx.draw_shell(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                          edge_color=edge_colour, node_color=node_colour)
        # elif graph_type == 'protein':
        # self.draw_protein(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
        #                   edge_color=edge_colour, node_color=node_colour, back_bone, side_chains, terminators)
        else:
            nx.draw_networkx(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        plt.show()
示例#2
0
 def __update_display(
     self,
     color_map={
         "healthy": "green",
         "asymptomatic": "orange",
         "symptomatic": "red",
         "dead": "gray"
     }):
     """__update_display - handles the display with matplotlib
     Inputs:
         - (Optional) color_map: an association dictionary for status->color
     Outputs:
         - None; displays as a window
     """
     plt.clf()
     plt.title(
         f"{self.__time_elapsed} / {self.__network_params['t']} - Number of Agents: {self.__num_agents}"
     )
     # get list of colorations
     colorations = self.__generate_colorations(color_map)
     # get list of labels
     labels = self.__generate_labels()
     # generate the lattice drawing
     nx.draw_spectral(self.__lattice, node_color=colorations, labels=labels)
     # update the display for animation-purposes
     plt.pause(0.05)
示例#3
0
def show_spectral_graph_embedding(graph):
    plt.figure()
    cmap = [purple, orange, blue]
    nodes = graph.nodes()
    colors = [cmap[graph.node[n]['label']] for n in nodes]
    nx.draw_spectral(graph, node_size=10, nodelist=nodes, node_color=colors)
    plt.show()
def tweet_flow():
    global graph

    print "Incoming Tweets!"
    hashtag_edges = []
    hastag_edges = get_edges_from_pairs(genereate_tags())
    graph = max(nx.connected_component_subgraphs(graph), key=len)
    for i in hastag_edges:
        if i[0] != i[1] and len(i[0]) > len(i[1]):
            graph.add_edge(i[0],i[1])

    calc_average_degree()


    nx.draw_spectral(graph,
    node_size = 300,  
    width = 100,  
    node_color = '#A0CBE2', #light blue
    edge_color = '#4169E1', #royal blue
    font_size = 10,
    with_labels = True )

    plt.draw()
    plt.pause(0.001)

    time.sleep(60)
    graph.clear()
    tweet_flow()
    def set_lane_direction_alternates(self):
        G2 = nx.DiGraph(self.g)
        for edge in G2.edges():
            if edge != tuple(sorted(edge)):
                G2.remove_edge(*edge)

        nx.draw_spectral(G2, node_size=600, node_color='w')
示例#6
0
    def plot(self):
        """
        function to plot the Graph
        :return: None
        """

        options = {
            'with_labels': True,
            'node_color': 'lightblue',  # blue
            'node_size': 1000,
            'node_shape': 's',  # 'd', '^', 'o',  '^',
            'font_size': 20,
            'font_weight': 'bold'
        }

        type_of_draw = 'kamada_kawai'
        # DRAW IN DIFFERENT LAYOUT
        if type_of_draw == 'planar':
            nx.draw_planar(self.Graph, **options)
        elif type_of_draw == 'spectral':
            nx.draw_spectral(self.Graph, **options)
        elif type_of_draw == 'kamada_kawai':
            nx.draw_kamada_kawai(self.Graph, **options)
        elif type_of_draw == 'spring':
            nx.draw_spring(self.Graph, **options)

        print("Plotting 4 You...")
        plt.draw()
        plt.show()
        # plt.savefig("saved_Plot4You.png")
        plt.clf()
示例#7
0
 def displayGraph(self, g, label=False):
     axon, sd = axon_dendrites(g)
     sizes = node_sizes(g) * 50
     if len(sizes) == 0:
         print('Empty graph for cell. Make sure proto file has `*asymmetric` on top. I cannot handle symmetric compartmental connections')
         return
     weights = np.array([g.edge[e[0]][e[1]]['weight'] for e in g.edges()])
     pos = nx.graphviz_layout(g, prog='twopi')
     xmin, ymin, xmax, ymax = 1e9, 1e9, -1e9, -1e9
     for p in list(pos.values()):
         if xmin > p[0]:
             xmin = p[0]
         if xmax < p[0]:
             xmax = p[0]
         if ymin > p[1]:
             ymin = p[1]
         if ymax < p[1]:
             ymax = p[1]        
     edge_widths = 10.0 * weights / max(weights)
     node_colors = ['k' if x in axon else 'gray' for x in g.nodes()]
     lw = [1 if n.endswith('comp_1') else 0 for n in g.nodes()]
     self.axes.clear()
     try:
         nx.draw_graphviz(g, ax=self.axes, prog='twopi', node_color=node_colors, lw=lw)
     except (NameError, AttributeError) as e:
         nx.draw_spectral(g, ax=self.axes, node_color=node_colors, lw=lw, with_labels=False, )
示例#8
0
def draw_networkx_ex():
    G = nx.dodecahedral_graph()
    nx.draw(G)
    plt.show()
    nx.draw_networkx(G, pos=nx.spring_layout(G))
    limits = plt.axis('off')
    plt.show()
    nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
    plt.show()
    edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    plt.show()
    labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
    plt.show()
    edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
    plt.show()
    print("Circular layout")
    nx.draw_circular(G)
    plt.show()
    print("Random layout")
    nx.draw_random(G)
    plt.show()
    print("Spectral layout")
    nx.draw_spectral(G)
    plt.show()
    print("Spring layout")
    nx.draw_spring(G)
    plt.show()
    print("Shell layout")
    nx.draw_shell(G)
    plt.show()
    print("Graphviz")
示例#9
0
def bfs(start):
    queue = [start]
    visitedVertex = []
    #while stack has some value in it
    while queue:
        #poping the last element
        current = queue.pop()
        for neighbor in adjacencyList[current]:
            #if value is not in visitedVertex then append stack
            if not neighbor in visitedVertex:
                # inserting at first position
                queue.insert(0, neighbor)

                ### visualizing ###
                c = ['r'] * len(vertexList)
                for i in visitedVertex:
                    c[i] = 'b'
                G.add_nodes_from(vertexList)
                G.add_edges_from(edgeList)
                nx.draw_spectral(G, with_labels=True, node_color=c)
                plt.show()

            else:
                c = ['r'] * len(vertexList)
                for i in visitedVertex:
                    c[i] = 'b'
                G.add_nodes_from(vertexList, node_color='g')
                G.add_edges_from(edgeList)
                nx.draw_spectral(G, with_labels=True, node_color=c)
                plt.show()
                ### visualizing ended ###

        visitedVertex.append(current)
    return visitedVertex
示例#10
0
def draw_networkx_ex():
    G = nx.dodecahedral_graph()
    nx.draw(G)
    plt.show()
    nx.draw_networkx(G, pos=nx.spring_layout(G))
    limits = plt.axis('off')
    plt.show()
    nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
    plt.show()
    edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    plt.show()
    labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
    plt.show()
    edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
    plt.show()
    print("Circular layout")
    nx.draw_circular(G)
    plt.show()
    print("Random layout")
    nx.draw_random(G)
    plt.show()
    print("Spectral layout")
    nx.draw_spectral(G)
    plt.show()
    print("Spring layout")
    nx.draw_spring(G)
    plt.show()
    print("Shell layout")
    nx.draw_shell(G)
    plt.show()
    print("Graphviz")
示例#11
0
def dfs(start):

    stack = [start]
    visitedVertex = []
    #while stack has some value in it
    while stack:
        current = stack.pop()
        G.remove_node(current)
        for neighbor in adjacencyList[current]:
            #if value is not in visitedVertex then append stack
            if not neighbor in visitedVertex:
                stack.append(neighbor)

                ### visualizing ###
                c = ['r'] * len(vertexList)
                for i in visitedVertex:
                    c[i] = 'b'
                G.add_nodes_from(vertexList)
                G.add_edges_from(edgeList)
                nx.draw_spectral(G, with_labels=True, node_color=c)
                plt.show()

            else:
                c = ['r'] * len(vertexList)
                for i in visitedVertex:
                    c[i] = 'b'
                G.add_nodes_from(vertexList, node_color='g')
                G.add_edges_from(edgeList)
                nx.draw_spectral(G, with_labels=True, node_color=c)
                plt.show()
                ### visualizing ended ###

        visitedVertex.append(current)

    return visitedVertex
示例#12
0
 def displayGraph(self, g, label=False):
     axon, sd = axon_dendrites(g)
     sizes = node_sizes(g) * 50
     if len(sizes) == 0:
         print(
             'Empty graph for cell. Make sure proto file has `*asymmetric` on top. I cannot handle symmetric compartmental connections'
         )
         return
     node_colors = ['k' if x in axon else 'gray' for x in g.nodes()]
     lw = [1 if n.endswith('comp_1') else 0 for n in g.nodes()]
     self.axes.clear()
     try:
         nx.draw_graphviz(g,
                          ax=self.axes,
                          prog='twopi',
                          node_color=node_colors,
                          lw=lw)
     except (NameError, AttributeError) as e:
         nx.draw_spectral(
             g,
             ax=self.axes,
             node_color=node_colors,
             lw=lw,
             with_labels=False,
         )
示例#13
0
def ministro_ministro(G):
    """
    Cria um grafo de ministros conectados de acordo com a sobreposição de seu uso da legislação
    Construido a partir to grafo ministro_lei
    """
    GM = nx.Graph()
    for m in G:
        try:
            int(m)
        except ValueError:# Add only if node is a minister
            if m != "None":
                GM.add_node(m.decode('utf-8'))
#    Add edges
    for n in GM:
        for m in GM:
            if n == m: continue
            if GM.has_edge(n,m) or GM.has_edge(m,n): continue
            # Edge weight is the cardinality of the intersection each node neighbor set.
            w = len(set(nx.neighbors(G,n.encode('utf-8'))) & set(nx.neighbors(G,m.encode('utf-8')))) #encode again to allow for matches
            if w > 5:
                GM.add_edge(n,m,{'weight':w})
    # abreviate node names
    GMA = nx.Graph()
    GMA.add_weighted_edges_from([(o.replace('MIN.','').strip(),d.replace('MIN.','').strip(),di['weight']) for o,d,di in GM.edges_iter(data=True)])
    P.figure()
    nx.draw_spectral(GMA)
    nx.write_graphml(GMA,'ministro_ministro.graphml')
    nx.write_gml(GMA,'ministro_ministro.gml')
    nx.write_pajek(GMA,'ministro_ministro.pajek')
    nx.write_dot(GMA,'ministro_ministro.dot')
    return GMA
示例#14
0
def start_graph(Nomserie, type_graph):
    print(type_graph)
    options = {
        'node_color': 'red',
        'node_size': 200,
        'width': 3,
    }

    if Nomserie == "Game of Thrones":
        G1 = nx.read_graphml("data/got/GoT_S05E09_1039.graphml")
        print(G1)
    if Nomserie == "Breaking Bad":
        G1 = nx.read_graphml("data/bb/BB_S03E11_598.graphml")
    if Nomserie == "House of Card":
        G1 = nx.read_graphml("data/hoc/HoC_S02E13_879.graphml")

    G1.remove_nodes_from(nx.isolates(G1))
    if type_graph == "Classical":
        nx.draw_networkx(G1, pos=nx.spring_layout(G1))
    if type_graph == "Random":
        nx.draw_random(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Circular":
        nx.draw_circular(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Spectral":
        nx.draw_spectral(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Shell":
        nx.draw_shell(G1, **options, with_labels=True, font_weight='bold')
    plt.savefig("images/" + Nomserie + "_" + type_graph + ".jpg")
    plt.close('all')
示例#15
0
def plot_graph(graph, type="shell", layout=None):
    cols = list()
    for n in graph.nodes:
        if graph.nodes[n]['state'] == "S":
            cols.append("blue")
        elif graph.nodes[n]['state'] == "I":
            cols.append("red")
        else:
            cols.append("green")
    options = {
        'node_color': cols,
        'node_size': 50,
        'width': 2,
    }
    if not layout is None:
        nx.draw(graph, pos=layout, **options)
    elif type == "shell":
        nx.draw_shell(graph, **options)
    elif type == "spectral":
        nx.draw_spectral(graph, **options)
    elif type == "spring":
        nx.draw_spring(graph, **options)
    else:
        nx.draw(graph, **options)
    return
示例#16
0
    def affiche(self):
        #Je recupere une liste de fitness des 20% meilleurs graphe
        listeBestFitness = []
        for i in range(len(self.listGraph)):
            #creation d'une liste de tuples
            listeBestFitness.append(
                (self.listGraph[i].ID, self.listGraph[i].fitness))
        listeBestFitness = sorted(listeBestFitness, key=self.getFitness)
        IDmemory = []
        f = open('bestfitness.txt', 'w')
        f.write('ID\tfitness\n')
        for j in range(1, int(len(listeBestFitness) * 20.0 / 100) + 1):
            IDmemory.append(listeBestFitness[-j][0])
            f.write('%i\t%f\n' % listeBestFitness[-j])
        f.close()

        #Liste des graphes correspondant aux 20% aillant la meilleure fitness
        BestListGraph = []
        for i in self.listGraph:
            if i.ID in IDmemory:
                BestListGraph.append(i)

        #print('best fitness :' + str(len(BestListGraph)))
        #Affichage de tous les graphes
        for k in BestListGraph:
            fig = plt.figure()
            deg = nx.degree(k.graph).values()
            nx.draw_spectral(k.graph,
                             node_size=10,
                             with_labels=False,
                             width=0.5,
                             node_color=deg,
                             cmap=plt.cm.Blues)
            plt.savefig('graphe_%i' % k.ID, format='png')
            plt.close(fig)
示例#17
0
def graph_statistics(g: nx.Graph, artifact_path: str):
    clustering_coeff = nx.average_clustering(g)
    density = nx.density(g)

    summary = io.StringIO()
    summary.write(f"{nx.info(g)}\n")
    summary.write(f"Clustering Coefficient: {clustering_coeff}\n")
    summary.write(f"Density: {density}\n")

    with open(f"{artifact_path}/summary.txt", "w") as f:
        f.write(summary.getvalue())
    print(summary.getvalue())

    plt.clf()
    nx.draw(g)
    plt.savefig(f"{artifact_path}/force_directed.png")

    plt.clf()
    nx.draw_spectral(g)
    plt.savefig(f"{artifact_path}/spectral.png")

    plt.clf()
    buckets = nx.degree_histogram(g)
    degrees = list(range(len(buckets)))
    plt.loglog(degrees, buckets)
    plt.savefig(f"{artifact_path}/degree_histogram.png")
 def draw_spectral_communities(self):
     partition = self.find_partition()[1]
     node_color=[float(partition[v]) for v in partition]
     labels = self.compute_labels()
     nx.draw_spectral(self.G,node_color=node_color, labels=labels)
     plt.show()
     plt.savefig("C:\\Users\\Heschoon\\Dropbox\\ULB\\Current trends of artificial intelligence\\Trends_project\\graphs\\graph_spectral.pdf")
def graph_trajectory(trajectory):
    """ plots unique state changes for input trajectory """
    source = trajectory.shift()
    target = trajectory

    # add subscripts so transitions are unique
    for i, r in source.iteritems():
        if r is not np.nan:
            source[i] = f'{r}$_{{{i-1}}}$'

    for i, r in target.iteritems():
        target[i] = f'{r}$_{{{i}}}$'

    df = pd.concat(
        [source, target],
        axis=1,
    ).reset_index(drop=True)
    df.columns = ['source', 'target']
    df = df.iloc[1:]  # drop first row with nan
    G = nx.from_pandas_edgelist(df,
                                'source',
                                'target',
                                create_using=nx.DiGraph())
    plt.figure(figsize=(20, 10), dpi=80, facecolor='w')
    nx.draw_spectral(G, with_labels=True, node_color='#d3d3d3')
    plt.show()
示例#20
0
文件: tass.py 项目: lgadawski/tass
def draw_graph(g, out_filename):
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)

    plt.savefig(out_filename)
示例#21
0
文件: tass.py 项目: lgadawski/tass
def draw_graph(g, out_filename):
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)

    plt.savefig(out_filename)
示例#22
0
def visualize_graph(adj_mat, burned, defended):
    g = nx.convert_matrix.from_numpy_matrix(adj_mat)
    node_color = np.where(burned, 1.0, 0.2)
    node_color = np.where(defended, 0.6, node_color)
    nx.draw_spectral(g, node_color=node_color.tolist())
    plt.plot()
    plt.show()
示例#23
0
 def drawgraph(self, G):
     nx.draw(G)
     plt.savefig(self.opts.o[0] + ".cluster_graph.png")
     nx.draw_random(G)
     plt.savefig(self.opts.o[0] + ".cluster_graph_random.png")
     nx.draw_circular(G)
     plt.savefig(self.opts.o[0] + ".cluster_graph_circular.png")
     nx.draw_spectral(G)
     plt.savefig(self.opts.o[0] + ".cluster_graph_spectral.png")
示例#24
0
文件: plot.py 项目: cipoll4/pymake
def draw_graph_spectral(y, clusters='blue', ns=30):
    G = nxG(y)
    pos = graphviz_layout(G, prog='twopi', args='')
    plt.figure()
    nx.draw_spectral(G,
                     cmap=plt.get_cmap('jet'),
                     node_color=clusters,
                     node_size=30,
                     with_labels=False)
示例#25
0
def test_pop():
    import matplotlib.pyplot as plt
    G = nx.DiGraph()
    search_query = sch.search_pubs_query('10.1109/THS.2013.6698999')
    P = search_query.next()
    P = P.fill()
    populate_graph(P, G)
    nx.draw_spectral(G)
    plt.show()
 def draw_spectral_communities(self):
     partition = self.find_partition()[1]
     node_color = [float(partition[v]) for v in partition]
     labels = self.compute_labels()
     nx.draw_spectral(self.G, node_color=node_color, labels=labels)
     plt.show()
     plt.savefig(
         "C:\\Users\\Heschoon\\Dropbox\\ULB\\Current trends of artificial intelligence\\Trends_project\\graphs\\graph_spectral.pdf"
     )
示例#27
0
def visualisation(chain, pairs):
    G = nx.Graph()

    a = range(len(chain))
    G.add_edges_from([(i, i + 1) for i in a[:-1]])

    G.add_edges_from(pairs)
    nx.draw_spectral(G)
    plt.show()
示例#28
0
def demo_save_fig():
    """demo_save_fig"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    plt.savefig("g.png")
示例#29
0
def _save_graph(graph, path):
    plt.figure(figsize=(10, 10))
    nx.draw_spectral(
        graph,
        node_color=(list(graph.nodes())),
        node_size=400,
        cmap=plt.cm.Blues,
        with_labels=True,
    )
    plt.savefig(path)
示例#30
0
def main():
    print("Graphing!")
    G = nx.Graph()
    G.add_nodes_from([1 - 3])
    G.add_edge(1, 2)

    nx.draw_random(G)
    nx.draw_circular(G)
    nx.draw_spectral(G)
    plt.show()
示例#31
0
文件: demo.plot.py 项目: gree2/hobby
def demo_save_fig():
    """demo_save_fig"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    plt.savefig("g.png")
示例#32
0
def main():
    print("Graphing!")
    G = nx.Graph()
    G.add_nodes_from([1-3])
    G.add_edge(1, 2)

    nx.draw_random(G)
    nx.draw_circular(G)
    nx.draw_spectral(G)
    plt.show()
示例#33
0
def drawGraph():
    time.sleep(15)
    log.info("Network's topology graph:")
    nx.draw_spectral(g)
    nx.draw_networkx_edge_labels(g,pos=nx.spectral_layout(g))
    #nx.draw_circular(g)
    #nx.draw_networkx_edge_labels(g,pos=nx.circular_layout(g))
    #nx.draw_shell(g)
    #nx.draw_networkx_edge_labels(g,pos=nx.shell_layout(g))
    plt.show()
示例#34
0
def demo_write_doc():
    """demo_write_doc"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    nx.draw_graphviz(g)
    nx.write_dot(g, 'g.dot')
示例#35
0
 def test_draw(self):
     #         hold(False)
     N = self.G
     nx.draw_spring(N)
     pylab.savefig("test.png")
     nx.draw_random(N)
     pylab.savefig("test.ps")
     nx.draw_circular(N)
     pylab.savefig("test.png")
     nx.draw_spectral(N)
     pylab.savefig("test.png")
示例#36
0
    def test_draw(self):
#         hold(False)
        N=self.G
        nx.draw_spring(N)
        pylab.savefig("test.png")
        nx.draw_random(N)
        pylab.savefig("test.ps")
        nx.draw_circular(N)
        pylab.savefig("test.png")
        nx.draw_spectral(N)
        pylab.savefig("test.png")
示例#37
0
文件: demo.plot.py 项目: gree2/hobby
def demo_write_doc():
    """demo_write_doc"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    nx.draw_graphviz(g)
    nx.write_dot(g, 'g.dot')
示例#38
0
def vis_graph(graph, image_path, mode='circular'):
    plt.figure(num=None, figsize=(20, 20), dpi=80)
    plt.axis('off')
    fig = plt.figure(1)
    if mode == 'spectral':
        nx.draw_spectral(graph)
    if mode == 'spring':
        nx.draw_spring(graph)
    if mode == 'circular':
        nx.draw_circular(graph)
    #plt.show()
    plt.savefig(image_path)
示例#39
0
    def _create_dependency_graph(self):
        dot = self.workflow.get_dot()
        dot_file = StringIO()
        dot_file.write(dot.source)
        dot_file.seek(0)

        graph = nx.drawing.nx_pydot.read_dot(dot_file)
        image = BytesIO()
        nx.draw_spectral(graph, with_labels=True)
        plt.savefig(image, format='png')

        return b64encode(image.getvalue()).decode()
def drawGraph():
    time.sleep(15)
    log.info("Network's topology graph:")
    log.info('  -> ingress switches: {}'.format(list(ingress)))
    log.info('  -> egress switches:  {}'.format(list(egress)))
    nx.draw_spectral(graph)
    nx.draw_networkx_edge_labels(graph, pos=nx.spectral_layout(graph))
    #nx.draw_circular(graph)
    #nx.draw_networkx_edge_labels(graph, pos=nx.circular_layout(graph))
    #nx.draw_shell(graph)
    #nx.draw_networkx_edge_labels(graph, pos=nx.shell_layout(graph))
    plt.show()
示例#41
0
    def show(self, mode=None):

        if not mode:
            nx.draw(self)
        elif mode == 'random':
            nx.draw_random(self)
        elif mode == 'circular':
            nx.draw_circular(self)
        elif mode == 'spectral':
            nx.draw_spectral(self)

        plt.show()
示例#42
0
def drawGraph():
    time.sleep(15)
    log.info("Network's topology graph:")
    log.info('  -> ingress switches: {}'.format(list(ingress)))
    log.info('  -> egress switches:  {}'.format(list(egress)))
    nx.draw_spectral(graph)
    nx.draw_networkx_edge_labels(graph, pos=nx.spectral_layout(graph))
    #nx.draw_circular(graph)
    #nx.draw_networkx_edge_labels(graph, pos=nx.circular_layout(graph))
    #nx.draw_shell(graph)
    #nx.draw_networkx_edge_labels(graph, pos=nx.shell_layout(graph))
    plt.show()
示例#43
0
文件: gui.py 项目: BhallaLab/moose
 def displayGraph(self, g, label=False):
     axon, sd = axon_dendrites(g)
     sizes = node_sizes(g) * 50
     if len(sizes) == 0:
         print('Empty graph for cell. Make sure proto file has `*asymmetric` on top. I cannot handle symmetric compartmental connections')
         return
     node_colors = ['k' if x in axon else 'gray' for x in g.nodes()]
     lw = [1 if n.endswith('comp_1') else 0 for n in g.nodes()]
     self.axes.clear()
     try:
         nx.draw_graphviz(g, ax=self.axes, prog='twopi', node_color=node_colors, lw=lw)
     except (NameError, AttributeError) as e:
         nx.draw_spectral(g, ax=self.axes, node_color=node_colors, lw=lw, with_labels=False, )
示例#44
0
 def test_draw(self):
     N=self.G
     nx.draw_spring(N)
     plt.savefig("test.ps")
     nx.draw_random(N)
     plt.savefig("test.ps")
     nx.draw_circular(N)
     plt.savefig("test.ps")
     nx.draw_spectral(N)
     plt.savefig("test.ps")
     nx.draw_spring(N.to_directed())
     plt.savefig("test.ps")
     os.unlink('test.ps')
示例#45
0
def GirvanNewman(G):
    no_component = nx.number_connected_components(G) #number of components 
    print("Number of components: ", no_component)
    number_comp = no_component
    while number_comp <= no_component: #while loop to partition graph into separate components 
        betweenness = nx.edge_betweenness_centrality(G)   #edge betweenness 
        highest = max(betweenness.values()) #highest betweenness
        print("Highest betweenness: ", highest)
        for key, value in betweenness.items():
            if float(value) == highest:
                print("Edge removed ", key[0],key[1])
                G.remove_edge(key[0],key[1])    #remove the edge with highest betweenness
                nx.draw_spectral(G) #draw graph after edge removed
                plt.show()
        number_comp = nx.number_connected_components(G)   #recalculate number of components                                         
        print("\nNumber of components: ", number_comp)    #print number of components
示例#46
0
    def to_nx_graph(self, aut):
        nx_graph = nx.MultiDiGraph(
            autosize=False,
            size="5.75,7.25",
            ranksep="0.9",
            splines=True,
            sep="+5, 5",
            overlap="false",
            nodesep="0.2",
            labelfontcolor="blue",
            labelloc="t",
            label=self.title_name,
        )
        nx_graph.add_nodes_from(
            list(aut.states), height="0.4", width="0.4", color="pink", style="filled", fixedsize=False, fontsize="11"
        )

        for k in aut.transitions.keys():
            for key, value in aut.transitions[k].items():
                for v in value:
                    nx_graph.add_edge(
                        k,
                        v,
                        color=(self.color_set[2])
                        if (key == "#")
                        else (self.color_set[list(aut.char_set).index(key) % len(list(aut.char_set))]),
                        arrowsize=0.5,
                        labeldistance=2.5,
                        penwidth="0.8",
                    )
        nx.draw_spectral(nx_graph)

        gv_graph = to_agraph(nx_graph)
        gv_graph.layout(prog="dot")
        # prog=neato|dot|twopi|circo|fdp|nop

        # set start & end states
        for node in gv_graph.nodes():
            if int(node.get_name()) in aut.e_states:
                node.attr["color"] = "green"
                node.attr["shape"] = "doublecircle"
            elif int(node.get_name()) in aut.s_states:
                node.attr["color"] = "blue"
                node.attr["shape"] = "diamond"
        gv_graph.draw("pics/" + str(self.pic_name) + ".png")

        return gv_graph
示例#47
0
 def test_draw(self):
     try:
         N = self.G
         nx.draw_spring(N)
         plt.savefig('test.ps')
         nx.draw_random(N)
         plt.savefig('test.ps')
         nx.draw_circular(N)
         plt.savefig('test.ps')
         nx.draw_spectral(N)
         plt.savefig('test.ps')
         nx.draw_spring(N.to_directed())
         plt.savefig('test.ps')
     finally:
         try:
             os.unlink('test.ps')
         except OSError:
             pass
示例#48
0
def __draw_dual_pivot__(G, pos, width, height, pivot, mapping, node_size, pivot_color, pivot_label):
    """
    Given a pivot, annotate it with color and label (handling duplicate if necessary) in dual.
    :param G: Graph.
    :param pos: position in canvas.
    :param pivot: pivot dart.
    :param mapping:
    :param node_size: size of nodes in drawing.
    :param pivot_color: pivot dart color.
    :param pivot_label:
    :return: Nothing.
    """
    # Use different color for pivot dart (Handle boundary duplication if necessary).
    pivot_dups = resolve_boundary_darts(
        mapping[pivot.dual.tail.name], mapping[pivot.dual.head.name]) if pivot != None else []
    pivot_dups = __remove_boundary_to_boundary_darts__(pivot_dups, width, height)
    nx.draw_spectral(G,node_size=node_size,edgelist=pivot_dups,width=3,edge_color=pivot_color,node_color='white')
    # Label pivot dart with pivot_label.
    nx.draw_networkx_edge_labels(G, pos, edge_labels=__pivot_labels__(pivot_dups, pivot_label), label_pos=0.5)
示例#49
0
def __draw_primal_pivot__(G, pos, pivot, mapping, node_size, pivot_color, pivot_label):
    """
    Given a pivot, annotate it with color and label (handling duplicate if necessary).
    :param G: Graph.
    :param pos: position in canvas.
    :param pivot: pivot dart.
    :param mapping:
    :param node_size: size of nodes in drawing.
    :param pivot_color: pivot dart color.
    :param pivot_label:
    :return: Nothing.
    """
    # Use different color for pivot dart (Handle boundary duplication if necessary).
    pivot_in_dups = resolve_boundary_darts(mapping[pivot.tail.name], mapping[pivot.head.name]) if \
        pivot is not None else []
    nx.draw_spectral(G,node_size=node_size,edgelist=pivot_in_dups,width=3,edge_color=pivot_color,arrows=True)
    # Annotate pivot dart label with "in".
    nx.draw_networkx_edge_labels(G, pos, edge_labels=__pivot_labels__(pivot_in_dups, pivot_label),
                                 label_pos=0.5,arrows=True)
示例#50
0
文件: Planner.py 项目: leopepe/GOApy
    def plot_graph(self, file_name: str='graph.png', label_nodes: bool=True, label_edges: bool=True):
        import matplotlib.pyplot as plt
        # pos = nx.spring_layout(self.graph)
        pos = nx.shell_layout(self.graph, dim=1024, scale=0.5)
        # pos = nx.random_layout(self.graph, dim=1024, scale=0.5)

        if label_edges:
            edge_labels = {
                (edge[0], edge[1]): edge[2]['object'] for edge in self.graph.edges(data=True)
            }
            nx.draw_networkx_edge_labels(self.graph, pos, edge_labels, font_size=5)

        if label_nodes:
            labels = {node[0]: node[1] for node in self.graph.nodes(data=True)}
            nx.draw_networkx_labels(self.graph, pos, labels, font_size=5, alpha=0.8)

        # nx.draw(self.graph, with_labels=True, arrows=True, node_size=80)
        nx.draw_spectral(self.graph, with_labels=True, arrows=True, node_size=80)
        plt.savefig(file_name, dpi=1024)
示例#51
0
def draw_all(graph):
    """ Draw all different layout types for graph """
    nx.draw(graph)
    plt.savefig(path + 'draw.png')
    plt.close()
    nx.draw_circular(graph)
    plt.savefig(path + 'draw_circular.png')
    plt.close()
    nx.draw_random(graph)
    plt.savefig(path + 'draw_random.png')
    plt.close()
    nx.draw_spectral(graph)
    plt.savefig(path + 'draw_spectral.png')
    plt.close()
    nx.draw_spring(graph)
    plt.savefig(path + 'draw_spring.png')
    plt.close()
    nx.draw_shell(graph)
    plt.savefig(path + 'draw_shell.png')
    plt.close()
示例#52
0
def try_different_layouts(graph):
    layout_dir = 'graph_layout'
    if not os.path.exists(layout_dir):
        os.mkdir('graph_layout')
    nx.draw_random(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'rand.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_circular(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'circular.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_spectral(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'spectral.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_networkx(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'networkx.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw(graph, pos=graphviz_layout(graph), with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4,
            edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'graphviz.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_shell(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'shell.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_spring(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'spring.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()
    def show(self):
        edges = self.getEdges(self.networkTopology)
        nodes = self.getNodes(self.networkTopology)
        
        G=nx.Graph()

        G.add_nodes_from(nodes)
        G.add_edges_from(edges)

        #print G.nodes()
        #print G.edges()

        pos=nx.graphviz_layout(G,prog='twopi',args='')
        #plt.figure(figsize=(8,8))
        # >>> nx.draw(G)
        # >>> nx.draw_random(G)
        # >>> nx.draw_circular(G)
        # >>> nx.draw_spectral(G)
        nx.draw_spectral(G) #,pos,node_size=300,alpha=0.5,node_color="blue", with_labels=True)
        #plt.axis('equal')
        #plt.savefig('circular_tree.png')
        plt.show()
示例#54
0
def nx_plot(r_graph, cols_names, simple=True, labels=None, graph_layout='shell',
               node_size=1600, node_color='blue', node_alpha=0.3,
               node_text_size=12,
               edge_color='blue', edge_alpha=0.3, edge_tickness=1,
               edge_text_pos=0.3,
               text_font='sans-serif'):
    
    #G = nx.Graph()
    dg = nx.DiGraph()
    edges = []
    np_amat = np.asarray(bnlearn.amat(r_graph))
    for ri in range(np_amat.shape[0]):
        for ci in range(np_amat.shape[1]):
            if np_amat[ri,ci] == 1:
                #G.add_edge(cols_names[ri],cols_names[ci])
                dg.add_edge(cols_names[ri],cols_names[ci])
                edges.append((cols_names[ri],cols_names[ci]))
                
    #import pdb;pdb.set_trace()
    if simple:            
        if graph_layout=='spectral':
            nx.draw_spectral(dg,font_size=node_text_size)
        elif graph_layout=='random':
            nx.draw_random(dg,font_size=node_text_size)  
        elif graph_layout=='circular':
            nx.draw_circular(dg,font_size=node_text_size)  
        elif graph_layout=='spring':
            nx.draw_spring(dg,font_size=node_text_size)  
        else:
            nx.draw(dg,font_size=node_text_size)
    else:
        draw_graph(edges,directed=True, labels=labels, graph_layout=graph_layout,
               node_size=node_size, node_color=node_color, node_alpha=node_alpha,
               node_text_size=node_text_size,
               edge_color=edge_color, edge_alpha=edge_alpha, edge_tickness=edge_tickness,
               edge_text_pos=edge_text_pos,
               text_font=text_font)
示例#55
0
def main():
    print "input_net module is the main code."
    EDGE_FILE = 'net-edges.dat'
    NODE_FILE = 'net-nodes.dat'

    # Asks user if network has been damaged.
    damage = raw_input("Type in 1 for DNA damage and 0 for no damage:  ")

    # These input calls are for the presence of damage to the system in the form of node or edge deletion.
    node_delete = str(raw_input("Type in node for deletion or none for no deletion: "))

    u = str(raw_input("Type in upstream node of edge for deletion or none for no deletion:  "))

    if u != 'none':
        v = str(raw_input("Type in downstream node of edge for deletion:  "))  
        edge_delete = u,v
    else:
        edge_delete = u

    # Reads in the network given any damage to nodes or edges.
    net = read_network_from_file(EDGE_FILE, NODE_FILE, node_delete, edge_delete)
    nodes_list = build_nodes_list(NODE_FILE, node_delete)

    # Prints edge list with corresponding weights.
    for u, v in net.edges():
        print u, v, net[u][v]['weight']

    # Prints node list
    print nodes_list

    #nx.draw(net)
    #nx.draw_random(net)
    #nx.draw_circular(net)
    nx.draw_spectral(net)

    plt.show()
示例#56
0
    def graph_pedigree(self, pedigree=None):
        """
        Method that graphs the given pedigree.

        Parameters
        ----------
        pedigree : {literal -> [literal]} (optional)
            Dictionary rep (adj. list) of pedigree graph. If none is provided,
            self.pedigree will be used.
        """
        if not pedigree:
            pedigree = self.pedigree

        G = self._construct_graph()

        # change drawing method to change the shape of the graph
        pos = nx.draw_spectral(G)
        nx.draw(G, pos)
        plt.show()
示例#57
0
    def dependency_map(self):
        r"""
        Create a graph of the dependency graph in a decent format

        See Also
        --------
        dependency_graph
        dependency_list

        """
        dtree = self.dependency_graph()
        fig = nx.draw_spectral(dtree,
                               with_labels=True,
                               arrowsize=50,
                               node_size=2000,
                               edge_color='lightgrey',
                               width=3.0,
                               font_size=32,
                               font_weight='bold')
        return fig
示例#58
0
		edges.append((a,b))

edges = sorted(list(set(edges)))
faces = {}
for i in range(60): 
	faces[i] = []

for i in range(len(edges)):
	a,b = edges[i]
	point1 = verticies[edges[i][0]]
	point2 = verticies[edges[i][1]]
	# pltEdges(point1, point2)
	faces[edges[i][0]].append(edges[i][1])
	G.add_edge(a,b)

nx.draw_spectral(G,with_labels=True, edge_color=range(90), edge_cmap=plt.cm.cool)
plt.show()

pent_nodes = [
(9,27,55,58,33),
(0,12,37,40,18),
(6,24,43,46,30),
(1,13,38,41,19),
(7,25,44,47,31),
(10,34,59,56,28),
(45,42,26,8,32),
(4,16,50,53,22),
(5,23,51,48,17),
(2,14,36,39,20),
(3,15,49,52,21),
(11,29,54,57,35)