Exemplo n.º 1
0
def main():

    G_igraph, G_nx, nodes_vector = generate_data()

    aca0, aca1 = separate_data_by_academy(nodes_vector, G_nx)

    print aca0.nodes()
    print aca1.nodes()

    plt.subplot(121)
    nx.draw_networkx(
        G=aca0,
        pos=nx.spring_layout(aca0),
        with_labels=True,
        node_color='g',
        edge_color='b',
        alpha=1)

    plt.axis('off')

    plt.subplot(122)
    nx.draw_networkx(
        G=aca1,
        pos=nx.spring_layout(aca1),
        with_labels=True,
        node_color='g',
        edge_color='b',
        alpha=1)

    plt.axis('off')
    plt.show()
Exemplo n.º 2
0
    def test_scale_and_center_arg(self):
        G = nx.complete_graph(9)
        G.add_node(9)
        vpos = nx.random_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        vpos = nx.spring_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        vpos = nx.spectral_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2, center=(4,5))
        # circular can have twice as big length
        vpos = nx.circular_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2*2, center=(4,5))
        vpos = nx.shell_layout(G, scale=2, center=(4,5))
        self.check_scale_and_center(vpos, scale=2*2, center=(4,5))

        # check default center and scale
        vpos = nx.random_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.spring_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.spectral_layout(G)
        self.check_scale_and_center(vpos, scale=1, center=(0.5,0.5))
        vpos = nx.circular_layout(G)
        self.check_scale_and_center(vpos, scale=2, center=(0,0))
        vpos = nx.shell_layout(G)
        self.check_scale_and_center(vpos, scale=2, center=(0,0))
Exemplo n.º 3
0
def test_layouts():
    G =nx.gnm_random_graph(10,15)

    rand = [nx.random_layout(G)]
    circ = [nx.circular_layout(G)]
    #shell = [nx.shell_layout(G)] #same as circular layout...
    spectral = [nx.spectral_layout(G)]
    tripod = [tripod_layout(G)]

    layouts = [rand,circ,spectral, tripod]
    regimes = ["random","circular","spectral", "tripod"]

    for layout in layouts:
        layout.append(nx.spring_layout(G,2,layout[0]))
        layout.append(iterate_swaps(G,layout[0]))
        layout.append(nx.spring_layout(G,2,layout[2]))
        layout.append(greedy_swapper(G,layout[0]))

    # Now have list of lists... Find lengths of edgecrossings...

    num_crossings = []
    for layout in layouts:
        for sublayout in layout:
            num_crossings.append(count_crosses(G,sublayout))

    names = []
    for regime in regimes:
        names.append(regime)
        names.append(regime + "-spring")
        names.append(regime + "-swap")
        names.append(regime + "-swap-spr")
        names.append(regime + "-greedy")

    return G, layouts, names, num_crossings
Exemplo n.º 4
0
def main():
    
    ### Undirected graph ###
    
    # Initialize model using the Petersen graph
    model=gmm.gmm(nx.petersen_graph())
    old_graph=model.get_base()
    model.set_termination(node_ceiling)
    model.set_rule(rand_add)
    
    # Run simualation with tau=4 and Poisson density for motifs
    gmm.algorithms.simulate(model,4)   

    # View results
    new_graph=model.get_base()
    print(nx.info(new_graph))
    
    # Draw graphs
    old_pos=nx.spring_layout(old_graph)
    new_pos=nx.spring_layout(new_graph,iterations=2000)
    fig1=plt.figure(figsize=(15,7))
    fig1.add_subplot(121)
    #fig1.text(0.1,0.9,"Base Graph")
    nx.draw(old_graph,pos=old_pos,node_size=25,with_labels=False)
    fig1.add_subplot(122)
    #fig1.text(0.1,0.45,"Simulation Results")
    nx.draw(new_graph,pos=new_pos,node_size=20,with_labels=False)
    fig1.savefig("undirected_model.png")
    
    ### Directed graph ###
    
    # Initialize model using random directed Barabasi-Albert model
    directed_base=nx.barabasi_albert_graph(25,2).to_directed()
    directed_model=gmm.gmm(directed_base)
    directed_model.set_termination(node_ceiling)
    directed_model.set_rule(rand_add)
    
    # Run simualation with tau=4 and Poisson density for motifs
    gmm.algorithms.simulate(directed_model,4)
    
    # View results
    new_directed=directed_model.get_base()
    print(nx.info(new_directed))
    
    # Draw directed graphs
    old_dir_pos=new_pos=nx.spring_layout(directed_base)
    new_dir_pos=new_pos=nx.spring_layout(new_directed,iterations=2000)
    fig2=plt.figure(figsize=(7,10))
    fig2.add_subplot(211)
    fig2.text(0.1,0.9,"Base Directed Graph")
    nx.draw(directed_base,pos=old_dir_pos,node_size=25,with_labels=False)
    fig2.add_subplot(212)
    fig2.text(0.1,0.45, "Simualtion Results")
    nx.draw(new_directed,pos=new_dir_pos,node_size=20,with_labels=False)
    fig2.savefig("directed_model.png")
    
    # Export files
    nx.write_graphml(model.get_base(), "base_model.graphml")
    nx.write_graphml(directed_model.get_base(), "directed_model.graphml")
    nx.write_graphml(nx.petersen_graph(), "petersen_graph.graphml")
Exemplo n.º 5
0
def getpositions(nodes, links, fixeditem=None):
    if nx_available:
        G = nx.Graph()
        G.add_nodes_from(nodes)
        G.add_edges_from(links)
        # print G.number_of_nodes()
        # print G.number_of_edges()
        # for line in nx.generate_adjlist(G):
        #    print(line)

        if fixeditem:
            # so this currently doesnt appear to work
            # the node now seems to fix into centre
            pos = {1: (0, 0)}
            fixlist = [1]
            return nx.spring_layout(G, 2, 0.8, pos=pos, fixed=fixlist)
        else:
            # print nx.spring_layout(G, 2, 1.5, iterations=50)
            # TO DO set above to 0,0 for all - object of this is to avoid failure but
            # probably will make calling optional shortly
            return nx.spring_layout(G, 2, 1.5, iterations=50)
    else:
        # lets assign 0,0 for now - might move to random
        nodedict = {}
        for node in nodes:
            nodedict[node] = (0, 0)
        return nodedict
Exemplo n.º 6
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")
Exemplo n.º 7
0
def draw_figures(problem, clique_collection, probability):
    """
    function to draw figure
    :param problem: input problem
    :param clique_collection: all collection lists of cliques
    :param probability: input probability
    :return: show and save the out figure from origin to k-cliques graph with probability
    """

    pos = nx.spring_layout(problem.G)
    pl.figure(1)
    pl.title("original figure with probability {p}".format(p=probability))
    nx.draw(problem.G, pos=pos)
    nx.draw_networkx_labels(problem.G, pos, font_size=10, font_family='sans-serif')
    pl.savefig("origin_with_prob_{p}.png".format(p=probability))
    # pl.show()

    for i in range(len(clique_collection)):
        new_nodes = []
        for n in problem.G.nodes():
            for li in clique_collection[i]:
                if n in li:
                    new_nodes.append(n)

        subgraph = problem.G.subgraph(new_nodes)
        pos = nx.spring_layout(problem.G)
        pl.figure()
        pl.title('{k} cliques with probability {p}'.format(k=i+3, p=probability))
        nx.draw(subgraph, pos=pos)
        nx.draw_networkx_labels(subgraph, pos, font_size=10, font_family='sans-serif')
        pl.savefig("{k}_cliq_with_prob_{p}.png".format(k=i+3, p=probability))
Exemplo n.º 8
0
def drawSprings(corrMatrix, kclusters, initialPosFileName, mult=1.1):
    """drawSprings draws two figures, one of the spring evolution at 9 timepoints, one of the initial vs. final.

    :param corrMatrix: a data object generated by kmeans cluster - has the correlations between objects.
    :type corrMatrix: dict - must have 'data' and 'proteins'
    :param kclusters: the number of kclusters used in the analysis (what was passed to kmeans)
    :type kclusters: int
    :param initialPosFileName: a string pointing to the initial positions of each node - see nierhausPositions.txt
    :type initialPosFileName: string
    :param mult: a float of the base of the exponent to exapand on in each spring interation
    :type mult: float
    :returns:  an array of figures - first is the evolution, second is the start and end.
    
    """
    G = nx.Graph()
    positions = readDataFile(initialPosFileName)
    initialNodePos = {positions['proteins'][i]: [float(positions['data'][i,0])/4.0, float(positions['data'][i,1])/5.0] for i in range(len(positions['proteins']))}
       
    [G.add_node(x) for x in corrMatrix['proteins']]

    connection = (lambda x,y: corrMatrix['data'][x][y])

    [G.add_edge(corrMatrix['proteins'][x],corrMatrix['proteins'][y], weight=connection(x,y)) for x in range(len(corrMatrix['proteins'])) for y in range(len(corrMatrix['proteins'])) if (connection(x,y)!=0)]
    weights = [G.get_edge_data(x[0],x[1])['weight'] for x in G.edges()]

    notes = pylab.figure()
    ax = notes.add_subplot(1,2,1, title="nierhaus positions_kclusters=" + str(kclusters))
    drawNodePos = initialNodePos
    yDiff = [initialNodePos[x][1] - drawNodePos[x][1] for x in drawNodePos.keys()]
    nx.draw_networkx(G, pos = drawNodePos,
                    node_size=600, node_color = yDiff, cmap = pylab.cm.RdBu, vmin=-1, vmax=1,
                    edge_color=weights, edge_vmin = 0, edge_vmax = kMeansRuns, edge_cmap = pylab.cm.autumn_r, width=2,
                    font_size=10, font_weight='bold')

    iters = int(mult**8)
    ax = notes.add_subplot(1,2,2, title="spring iteration=" + str(iters) + "_kclusters=" + str(kclusters))
    drawNodePos = nx.spring_layout(G, pos=initialNodePos, iterations=iters)
    yDiff = [initialNodePos[x][1] - drawNodePos[x][1] for x in drawNodePos.keys()]
    nx.draw_networkx(G, pos = drawNodePos,
                    node_size=600, node_color = yDiff, cmap = pylab.cm.RdBu, vmin=-1, vmax=1,
                    edge_color=weights, edge_vmin = 0, edge_vmax = kMeansRuns, edge_cmap = pylab.cm.autumn_r, width=2,
                    font_size=10, font_weight='bold')

    cb1ax = notes.add_axes([0.025, 0.1, 0.05, 0.8])
    pylab.colorbar(cmap=pylab.cm.autumn_r, cax=cb1ax)
    cb2ax = notes.add_axes([0.925, 0.1, 0.05, 0.8])
    norm = mpl.colors.Normalize(vmin=-1, vmax=1)
    cb2 = mpl.colorbar.ColorbarBase(cb2ax, cmap=pylab.cm.RdBu_r, norm=norm, orientation='vertical')
        
    notes2 = pylab.figure()
    drawNodePos = initialNodePos
    for i in range(9):
        ax = notes2.add_subplot(3,3,i+1, title="iterations=" + str(int(mult**i)) + "_k=" + str(kclusters))
        drawNodePos = nx.spring_layout(G, pos=drawNodePos, iterations=int(mult**i))

        yDiff = [initialNodePos[x][1] - drawNodePos[x][1] for x in drawNodePos.keys()]
        nx.draw_networkx(G, pos = drawNodePos,
                        node_size=600, node_color = yDiff, cmap = pylab.cm.RdBu, vmin=-1, vmax=1,
                        edge_color=weights, edge_vmin = 0, edge_vmax = kMeansRuns, edge_cmap = pylab.cm.autumn_r, width=2,
                        font_size=10, font_weight='bold')
def paint_clusters(G1, G2, beacons_G1, beacons_G2, kmeans_labels1, kmeans_labels2):
	accent_colors = brewer2mpl.get_map('Accent', 'qualitative',8).mpl_colors
	plt.subplot(121)
	plt.axis('off')
	plt.title('$G_1$')
	(labels, node_colors, node_sizes) = visualize_beacons(G1, beacons_G1)
	clustered_colors = cluster_colors(G1, beacons_G1, kmeans_labels1, accent_colors)

	pos = nx.spring_layout(G1, weight=None)
	nx.draw_networkx_nodes(G1, pos, node_color=clustered_colors, node_size=node_sizes, font_size=18)
	nx.draw_networkx_labels(G1, pos, font_size=17, labels=labels, font_color = '#262626')
	nx.draw_networkx_edges(G1, pos, width=2, alpha=0.3)


	plt.subplot(122)
	plt.axis('off')
	plt.title('$G_2$')
	(labels, node_colors, node_sizes) = visualize_beacons(G2, beacons_G2)
	clustered_colors = cluster_colors(G2, beacons_G2, kmeans_labels2, accent_colors)

	pos2_init= {key:value for (key, value) in zip(beacons_G2,[pos[beacon] for beacon in beacons_G1])}
	pos2 = nx.spring_layout(G2, weight=None, pos = pos2_init)

	nx.draw_networkx_nodes(G2, pos=pos2, node_color=clustered_colors, node_size=node_sizes, font_size=18)
	nx.draw_networkx_labels(G2, pos=pos2, font_size=17, labels=labels, font_color = '#262626')
	nx.draw_networkx_edges(G2, pos=pos2, width=2, alpha=0.3)
Exemplo n.º 10
0
 def OnLocalPerturbation(self,e):
     k=0
     dlg=wx.NumberEntryDialog(self,message='The Number of nodes in cluster, default 3!',prompt='k:',caption='k-anonymity parameter',value=3,min=2,max=40)
     if (dlg.ShowModal() == wx.ID_OK):
         k=dlg.GetValue()
     else:
         return
     self.rtb.SetValue("")
     self.PushStatusText("Starting Local Perturbation", SB_INFO)
     self.ShowPos()
     if len(self.g.node)!=0:
         origin_g=self.g.copy()
         result=lp.LocalPerturbation(self.g,k)#perturbation and get the clusters and new graph
         self.g=result[1]
         OutStr="the clusters:\n"
         for c in result[0]:
             OutStr=OutStr+str(tuple(c))+"\n"
         self.rtb.SetValue(OutStr)
         plt.figure("comparison")
         plt.subplot(211)
         plt.title ("original graph")
         nx.draw(origin_g,with_labels=True,pos=nx.spring_layout(origin_g))
         plt.subplot(212)
         plt.title("new graph")
         nx.draw(self.g,with_labels=True,pos=nx.spring_layout(self.g))
         plt.show()
     else:
         print 'Grap is empty!! Please load data!'
         wx.MessageBox("No data was selected. Please load data!","Data Error")
Exemplo n.º 11
0
def Asymmetric_Networks():
	G_asymmetric = nx.DiGraph()
	G_asymmetric.add_edge('A', 'B')
	G_asymmetric.add_edge('A', 'D')
	G_asymmetric.add_edge('C', 'A')
	G_asymmetric.add_edge('D', 'E')
	nx.spring_layout(G_asymmetric)
	nx.draw_networkx(G_asymmetric)
Exemplo n.º 12
0
def add_ndex_spring_layout_with_attractors(g, node_width, attractor_map, iterations=None, use_degree_edge_weights=False):
    fixed = []
    initial_pos = {}
    g_simple = _create_simple_graph(g)
    next_node_id = max(g_simple.nodes()) + 1

    cc = sorted(nx.connected_components(g_simple), key = len, reverse=True)
    if len(cc) > 1:
        print("%s disconnected subgraphs: adding centerpoint attractor with edges to one of the least connected nodes in each subgraph" % len(cc))
        anchor_node_ids = []
        for c in cc:
            cl = list(c)
            min_degree = min(cl)
            min_index = cl.index(min_degree)
            node_id = cl[min_index]
            anchor_node_ids.append(node_id)
        attractor_id = next_node_id
        g_simple.add_node(next_node_id)
        next_node_id = next_node_id + 1
        fixed.append(attractor_id)
        initial_pos[attractor_id] = (0.5, 0.5)
        for node_id in anchor_node_ids:
            g_simple.add_edge(node_id, attractor_id)



    for attractor in attractor_map:
        attractor_id = next_node_id
        g_simple.add_node(next_node_id)
        next_node_id = next_node_id + 1
        fixed.append(attractor_id)
        initial_pos[attractor_id] = attractor["position"]
        for node_id in attractor["node_ids"]:
            g_simple.add_edge(node_id, attractor_id) # , {"weight":2.5})

    if use_degree_edge_weights:
        _add_degree_edge_weights(g_simple)

    scaled_pos = {}
    scale_factor = 4 * node_width * math.sqrt(g.number_of_nodes())

    for node in g_simple.nodes():
        x_pos = random.random() * scale_factor
        y_pos = random.random() * scale_factor
        scaled_pos[node] = (x_pos, y_pos)

    for node_id in initial_pos:
        position = initial_pos[node_id]
        scaled_pos[node_id] = (scale_factor * position[0], scale_factor * position[1])

    if len(fixed) > 0:
        final_positions = nx.spring_layout(g_simple, fixed=fixed, pos=scaled_pos, iterations=iterations)
        for node_id in fixed:
            final_positions.pop(node_id)
    else:
        final_positions = nx.spring_layout(g_simple, pos=scaled_pos, iterations=iterations)

    g.pos = final_positions
Exemplo n.º 13
0
 def test_algo_euler4(self):
     fLOG (__file__, self._testMethodName, OutputPrint = __name__ == "__main__")
     folder = os.path.join(os.path.abspath(os.path.dirname(__file__)),"temp_rues5")
     if not os.path.exists(folder) : os.mkdir(folder)
     edges = get_data(whereTo=folder)
     edges = edges[:3]
     
     vertices = { }
     for e in edges :
         for i in range(0,2):
             _ = e[i]
             p = e[i+3]
             vertices[_] = p
     
     connex = connected_components(edges)
     v = [ v for k,v in connex.items() ]
     mi,ma = min(v), max(v)
     
     while mi != ma :
         edges.append( (mi, ma, 2, vertices[mi], vertices[ma], 
                 distance_haversine( * (vertices[mi] + vertices[ma]) ) ) )
         
         connex = connected_components(edges)
         v = [ v for k,v in connex.items() ]
         mi,ma = min(v), max(v)
         
     if __name__ == "__main__":
         import matplotlib.pyplot as plt
         import networkx as nx
         fig = plt.figure()
         G = nx.Graph()
         for e in edges :
             a,b = e[:2]
             G.add_edge(a,b)
         pos = nx.spring_layout(G)
         nx.draw(G,pos,node_color='#A0CBE2')
         plt.savefig(os.path.join(folder, "graph1.png"))
         
     added = eulerien_extension( edges, fLOG=lambda *l : None, 
                                 distance = distance_paris)
                                 
     if __name__ == "__main__":
         for e in added :
             a,b = e[:2]
             G.add_edge(a,b)
         fig = plt.figure()
         pos = nx.spring_layout(G)
         deg = graph_degree(edges + added)
         #labels={ v:"{0}".format(deg[v]) for v in G.nodes() }
         nx.draw(G,pos,node_color='#A0CBE2'#,labels=labels
                         )
         plt.savefig(os.path.join(folder, "graph2.png"))
                                 
     path = euler_path(edges, added)
     all = edges + added
     fLOG(len(all),len(path))
def display(Y):
	weight 			= 0.03

	node_size 		= 50
	node_alpha 		= 0.5
	node_color 		= "blue"

	edge_tickness 	= 0.5
	edge_alpha 		= 0.5
	edge_color 		= "black"

	scores 	= get_histogram(Y)
	F 	= plt.figure()
	ax1 = F.add_subplot(2,2,1)
	ax1.hist(scores,bins=30, color="green", edgecolor="white")
	ax1.set_xlabel("Pearons Correlation Coefficient")
	ax1.set_ylabel("Frequency")

	ax2 = F.add_subplot(2,2,2)
	G 	= make_network(Y,threshold=0.95,weight=weight)
	pos = nx.spring_layout(G)	
	nx.draw(G, pos,ax=ax2,node_size=15)
	nx.draw_networkx_nodes(G,pos,node_size=node_size, 
		alpha=node_alpha, node_color=node_color)
	nx.draw_networkx_edges(G,pos,width=edge_tickness,
		alpha=edge_alpha,edge_color=edge_color)

	ax2.set_title("Network Thresholded, > 0.95")



	ax3 = F.add_subplot(2,2,3)
	ax3.set_title("Network Thresholded, > 0.55")
	G 	= make_network(Y,threshold=0.55,weight=weight)
	pos = nx.spring_layout(G)	
	nx.draw(G, pos,ax=ax3,node_size=15)
	nx.draw_networkx_nodes(G,pos,node_size=node_size, 
		alpha=node_alpha, node_color=node_color)
	nx.draw_networkx_edges(G,pos,width=edge_tickness,
		alpha=edge_alpha,edge_color=edge_color)



	ax4 = F.add_subplot(2,2,4)

	penalties 	= np.linspace(0.0, 1.0,20)

	counts 		= [len([x for x in nx.connected_components(make_network(Y,threshold=p, weight=1,add=True))]) for p in penalties]
	ax4.plot(penalties, counts)
	ax4.scatter(penalties, counts)
	ax4.set_xlabel("Pearon's Treshold")
	ax4.set_ylabel("Number of Connected Components")

	plt.tight_layout()
	plt.show()
def create_plot1(g, df=None, dedirect=False, flatten=False, edgelabels = True, 
          nodelabels=True, fsize=None, K=None, save=False):
                  
    """Creates a graph from a figure   
    returns/shows a figure.
    
    Args:
    g - (networkx graph object)
    df - pandas dataframe object. Default is None
    dedirect - converts networkx DiGraph to Graph. Default is False
    flatten - manipultes a graph by replacing nodes that have only two 
    edges with straighforward edge. Also, groups these kind of edges if
    it is possible
    
    
    edgelabels . Default is None
    nodelables . Default is None
    fsize
    K
    Save
    
    Returns:
    matplotlib figure
    
    """
    
    if dedirect==True:
        g = nx.Graph(g)
        
    if fsize != None:
        plt.figure(1, figsize=fsize)
    pos = nx.spring_layout(g, dim=2, scale=1)
    
    if flatten == True:
        g = flatten_graph(g)
        pos = nx.spring_layout(g, dim=2, scale=1)
    
    pos = nx.spring_layout(g, dim=2, scale=10, k=K)
    
    node_colors = get_node_colors(g.nodes(), df)
    nx.draw_networkx_nodes(g, pos, alpha=0.3, node_size=300, node_color=node_colors)
    
    edge_colors = get_edge_colors(g.edges(), df)
    nx.draw_networkx_edges(g, pos, alpha=0.1, edge_color='b')
    
    if nodelabels == True:
        nx.draw_networkx_labels(g, pos)
        
    if edgelabels == True:
        nx.draw_networkx_edge_labels(g, pos)
        
    if save == True:
        mpld3.save_html(figure(1), 'graph.html')
        
    return plt.figure(1)
Exemplo n.º 16
0
def test_plot(image):
    graph = nx.from_numpy_matrix(image)
    plt.subplot2grid((9, 3), (0, 0), rowspan=3, colspan=3)
    nx.draw(graph, nx.spring_layout(graph))
    plt.hold(True)
    plt.subplot2grid((9, 3), (3, 0), rowspan=3, colspan=3)
    nx.draw(graph, nx.spring_layout(graph))
    plt.hold(True)
    plt.subplot2grid((9, 3), (6, 0), rowspan=3, colspan=3)
    nx.draw(graph, nx.spring_layout(graph))
    plt.axis('tight')
    plt.show()
Exemplo n.º 17
0
def plot_graph(graph, fixed=None, positions=None, show_plot=True, fpath=None):
    """Plot graph.
    
    Parameters
    ----------
    graph : networkx.MultiDiGraph
        Output from `make_graph`
    fixed : {None}, list, optional
        Node around which to fix graph. Overrides `positions`.
        Example: fixed=['mod1']
    positions : {None}, dict, optional
        ``dict`` of ``list`` output from `make_positions_dict`.
        Requires `fixed` is ``None``, otherwise overridden. 
    show_plot : {True, False}, bool, optional
        Flag to display plot in window.
    fpath : {None}, string, optional
        Path for plotting graph.
    
    Returns
    -------
    None
    
    See Also
    --------
    CALLS : {}
    CALLED_BY : {}
    RELATED : {make_positions_dict, make_graph}

    """
    # TODO: Space out points. Scale to larger image?
    # TODO: make relationships different colors
    # Check input and define positions.
    if fixed is None:
        if positions is None:
            pos = nx.spring_layout(graph, fixed=fixed)
        else:
            pos = positions
    else:
        if positions is not None:
            warnings.warn(
                ("\n" +
                 "`fixed` overrides `positions`:\n" +
                 "fixed = {fixed}").format(
                     fixed=fixed))
        pos = nx.spring_layout(graph, fixed=fixed)
    # Draw graph and save.
    nx.draw(graph, pos=pos)
    nx.draw_networkx_labels(graph, pos=pos)
    if fpath is not None:
        plt.savefig(fpath, bbox_inches='tight')
    plt.show()
    return None
Exemplo n.º 18
0
def autoCoordinates(meshEntry,srcdesConnection):
    #for cmpt,memb in meshEntry.items():
    #    print memb
    xmin = 0.0
    xmax = 1.0
    ymin = 0.0
    ymax = 1.0
    G = nx.Graph()
    for cmpt,memb in meshEntry.items():
        for enzObj in find_index(memb,'enzyme'):
            G.add_node(enzObj.path)
    for cmpt,memb in meshEntry.items():
        for poolObj in find_index(memb,'pool'):
            G.add_node(poolObj.path)
        for cplxObj in find_index(memb,'cplx'):
            G.add_node(cplxObj.path)
            G.add_edge((cplxObj.parent).path,cplxObj.path)
        for reaObj in find_index(memb,'reaction'):
            G.add_node(reaObj.path)
        
    for inn,out in srcdesConnection.items():
        if (inn.className =='ZombieReac'): arrowcolor = 'green'
        elif(inn.className =='ZombieEnz'): arrowcolor = 'red'
        else: arrowcolor = 'blue'
        if isinstance(out,tuple):
            if len(out[0])== 0:
                print inn.className + ':' +inn[0].name + "  doesn't have input message"
            else:
                for items in (items for items in out[0] ):
                    G.add_edge(element(items[0]).path,inn.path)
            if len(out[1]) == 0:
                print inn.className + ':' + inn[0].name + "doesn't have output mssg"
            else:
                for items in (items for items in out[1] ):
                    G.add_edge(inn.path,element(items[0]).path)
        elif isinstance(out,list):
            if len(out) == 0:
                print "Func pool doesn't have sumtotal"
            else:
                for items in (items for items in out ):
                    G.add_edge(element(items[0]).path,inn.path)
    
    nx.draw(G,pos=nx.spring_layout(G))
    #plt.savefig('/home/harsha/Desktop/netwrokXtest.png')
    xcord = []
    ycord = []
    position = nx.spring_layout(G)
    for y in position.values():
        xcord.append(y[0])
        ycord.append(y[1])
	    
    return(min(xcord),max(xcord),min(ycord),max(ycord),position)
Exemplo n.º 19
0
def main(G):
    """draw the input graph and the colored out put graph
       determine the centroides and clusters
    """    
    try:
        val_map = {'A': 1.0,
                           'D': 0.5714285714285714,
                                      'H': 0.0}
        values = [val_map.get(node, 0.45) for node in G.nodes()]
        edge_colors = 'k'
        
        edge_labels=dict([((u,v,),d['weight'])
                     for u,v,d in G.edges(data=True)])
        pos=nx.spring_layout(G) # positions for all nodes                
        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
        nx.draw(G,pos, node_color = values, node_size=15,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
        pylab.show()
    
    
        km = BKM.KMeans(G, n_clusters, max_iter=100)
        
        
        pos=nx.spring_layout(G) # positions for all nodes
        node_colors = ['b','g','r','y','c','k','m'] 
        for i in range(len(G)):
                node_colors.append('w')
        # nodes
        Clust = km.fit_predict(G)[1]
        
        
        for item in range(n_clusters):
            for group in Clust[item]:
                nx.draw_networkx_nodes(G,pos,
                                       nodelist = Clust[item],
                                       node_color=node_colors[item],
                                       node_size=80,
                                   alpha=0.8)
        
        edge_colors = 'k'
        edge_labels=dict([((u,v,),d['weight'])
                     for u,v,d in G.edges(data=True)])               
        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
        nx.draw(G,pos, node_color = values, node_size=1,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
        pylab.show()
    
        print(km.__str__())


    except BKM.KMeansError:
        
        print( "Got an imput error, please change the input and try it again." )
Exemplo n.º 20
0
def main(G):
    """draw the input graph and the colored out put graph
       determine the clusters after each level of merging
    """    
    try:
        val_map = {'A': 1.0,
                           'D': 0.5714285714285714,
                                      'H': 0.0}
        values = [val_map.get(node, 0.45) for node in G.nodes()]
        edge_colors = 'k'
        
        edge_labels=dict([((u,v,),d['weight'])
                     for u,v,d in G.edges(data=True)])
        pos=nx.spring_layout(G) # positions for all nodes                
        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
        nx.draw(G,pos, node_color = values, node_size=15,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
        pylab.show()
    
        for ite in range(len(G.nodes())):
              
            Iterations = ite 
            AL = AVG.Average_linkage(G, Iterations)
            #print(AL.__str__())
            pos=nx.spring_layout(G) # positions for all nodes
            node_colors = ['b','g','r','y','c','k','m'] 
            for i in range(len(G)):
                node_colors.append('w')
            
            # nodes
            C_list = AL.fit_predict(G)[-1,:]
            for Clust in range(C_list.shape[1]):
                    nx.draw_networkx_nodes(G,pos,
                                           nodelist = list(C_list[0,Clust]),
                                           node_color=node_colors[Clust],
                                           node_size=80,
                                           alpha=0.8)
             
            # edges
            nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5)
            nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
            
            plt.axis('off')
            plt.savefig("labels_and_colors.png") # save as png
            plt.show() # display
            print "in level :",ite 
            print AL.__str__()


    except AVG.Average_linkage_Error:
        
        print( "Got an imput error, please change the input and try it again." )
Exemplo n.º 21
0
 def test_empty_graph(self):
     G=nx.Graph()
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.shell_layout(G)
     vpos = nx.spectral_layout(G)
     # center arg
     vpos = nx.random_layout(G, scale=2, center=(4,5))
     vpos = nx.circular_layout(G, scale=2, center=(4,5))
     vpos = nx.spring_layout(G, scale=2, center=(4,5))
     vpos = nx.shell_layout(G, scale=2, center=(4,5))
     vpos = nx.spectral_layout(G, scale=2, center=(4,5))
Exemplo n.º 22
0
def main(G):
    """draw the input graph and the colored out put graph
       determine the clusters after each level of merging
    """
    try:
        val_map = {'A': 1.0,
                           'D': 0.5714285714285714,
                                      'H': 0.0}
        values = [val_map.get(node, 0.45) for node in G.nodes()]
        edge_colors = 'k'

        edge_labels=dict([((u,v,),d['weight'])
                     for u,v,d in G.edges(data=True)])
        pos=nx.spring_layout(G) # positions for all nodes
        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
        nx.draw(G,pos, node_color = values, node_size=15,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
        pylab.show()

        SC = SCl.SpecClust(G, n_cluster)
        pos=nx.spring_layout(G) # positions for all nodes
        node_colors = ['b','g','r','y','c','k','m']
        for i in range(len(G)):
                node_colors.append('w')
        Cluster_for_index = SC.fit_predict(G)

        for i in range(n_cluster):
            Nodes = []
            for j in Cluster_for_index[i]:
                Nodes.append(G.nodes()[j])



            nx.draw_networkx_nodes(G,pos,
                                   nodelist = Nodes,
                                   node_color=node_colors[i],
                                   node_size=80,
                               alpha=0.8)
        edge_colors = 'k'
        edge_labels=dict([((u,v,),d['weight'])
                     for u,v,d in G.edges(data=True)])
        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
        nx.draw(G,pos, node_color = values, node_size=1,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
        pylab.show()

        print (SC.__str__())


    except SCl.SpecClust_error:

        print( "Got an imput error, please change the input and try it again." )
Exemplo n.º 23
0
 def test_single_node(self):
     G = nx.Graph()
     G.add_node(0)
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.shell_layout(G)
     vpos = nx.spectral_layout(G)
     # center arg
     vpos = nx.random_layout(G, scale=2, center=(4,5))
     vpos = nx.circular_layout(G, scale=2, center=(4,5))
     vpos = nx.spring_layout(G, scale=2, center=(4,5))
     vpos = nx.shell_layout(G, scale=2, center=(4,5))
     vpos = nx.spectral_layout(G, scale=2, center=(4,5))
Exemplo n.º 24
0
def getpositions(nodes, links, fixeditem=None):
    if nx_available:
        G = nx.Graph()
        G.add_nodes_from(nodes)
        G.add_edges_from(links)
        if fixeditem:
            #so this currently doesnt appear to work 
            #the node now seems to fix into centre
            pos = {1:(0,0)}
            fixlist = [1]
            return nx.spring_layout(G, 2, 0.7, pos=pos, fixed=fixlist)
        else:
            return nx.spring_layout(G, 2, 0.7)
    else:
        return dict(bla='bla')
Exemplo n.º 25
0
    def plot(self, **kwargs):
        """Plots the underlying graph."""

        plt.figure(facecolor='#fefefe', dpi=80, frameon=True) 
        plt.axis('off')
       
        try:
            positions = nx.graphviz_layout(self.graph)
        except ImportError as err:
            log.info('Graphviz not available: error=%s', err)
            log.info('Falling back to spring layout...')
            positions = nx.spring_layout(self.graph)
        #FIXME: Caused by bin/coffea in some cases
        except TypeError as err:
            log.warn('Graphviz layout failed: error=%s', err)
            log.warn('Falling back to spring layout...')
            positions = nx.spring_layout(self.graph)
   
        if 'calc_node_size' in kwargs and kwargs['calc_node_size']:
            node_size = self._node_size_vector
            if node_size is None:
                node_size = 300
        else:  
            node_size = 300 
            
        log.debug('Drawing nodes...') 
        nx.draw_networkx_nodes(self.graph, positions, 
                               node_color=self.node_colors, 
                               node_size=node_size,
                               alpha=0.8)
        
        log.debug('Drawing edges...') 
        nx.draw_networkx_edges(self.graph, positions, 
                               edge_color='#666666', 
                               alpha=0.75)
        
        log.debug('Drawing labels...') 
        nx.draw_networkx_labels(self.graph,positions, 
                                font_color='#222222', 
                                font_family='courier new',
                                font_weight='bold')
        
        log.debug('Plotting graph...')
        try: 
            filename = kwargs['filename']
            plt.savefig(filename, bbox_inches='tight')
        except KeyError:
            plt.show()
Exemplo n.º 26
0
  def drawFactorGraph(self,var_color='w',factor_color=(.2,.2,.8),**kwargs):
    """Draw a factorgraph using networkx function calls

    Args:
      var_color (str, tuple): networkx color descriptor for drawing variable nodes
      factor_color (str, tuple): networkx color for drawing factor nodes
      var_labels (dict): variable id to label string for variable nodes
      factor_labels (dict): factor id to label string for factor nodes
      ``**kwargs``: remaining keyword arguments passed to networkx.draw()

    Example:
    >>> model.drawFactorGraph( var_labels={0:'0', ... } )    # keyword args passed to networkx.draw()
    """
    # TODO: specify var/factor shape,size, position, etc.; return G? silent mode?
    import networkx as nx
    G = nx.Graph()
    vNodes = [v.label for v in self.X if v.states > 1]   # list only non-trivial variables
    fNodes = [-i-1 for i in range(len(self.factors))]    # use negative IDs for factors
    G.add_nodes_from( vNodes )
    G.add_nodes_from( fNodes )
    for i,f in enumerate(self.factors):
      for v1 in f.vars:
        G.add_edge(v1.label,-i-1)
   
    pos = nx.spring_layout(G)   # so we can use same positions multiple times...
    kwargs['var_labels']  = kwargs.get('var_labels',{n:n for n in vNodes})
    kwargs['labels'] = kwargs.get('var_labels',{})
    nx.draw_networkx(G,pos, nodelist=vNodes,node_color=var_color,**kwargs)
    kwargs['labels'] = kwargs.get('factor_labels',{})    # TODO: need to transform?
    nx.draw_networkx_nodes(G,pos, nodelist=fNodes,node_color=factor_color,node_shape='s',**kwargs)
    nx.draw_networkx_edges(G,pos,**kwargs)
    return G
Exemplo n.º 27
0
def display_retweet_network(network, outfile=None, show=False):
    """
    Take a DiGraph (retweet network?) and display+/save it to file.
    Nodes must have a 'color' property, represented literally and indicating their type
    Edges must have a 'weight' property, represented as edge width
    """
    import networkx as nx
    import matplotlib.pyplot as plt

    # Create a color list corresponding to nodes.
    node_colors = [ n[1]["color"] for n in network.nodes(data=True) ]

    # Get edge weights from graph
    edge_weights = [ e[2]["weight"] for e in network.edges(data=True) ]

    # Build up graph figure
    #pos = nx.random_layout(network)
    pos = nx.spring_layout(network)
    nx.draw_networkx_edges(network, pos, alpha=0.3 , width=edge_weights, edge_color='m')
    nx.draw_networkx_nodes(network, pos, node_size=400, node_color=node_colors, alpha=0.4)
    nx.draw_networkx_labels(network, pos, fontsize=6)

    plt.title("Retweet Network", { 'fontsize': 12 })
    plt.axis('off')

    if outfile:
        print "Saving network to file: {0}".format(outfile)
        plt.savefig(outfile)

    if show:
        print "Displaying graph. Close graph window to resume python execution"
        plt.show()
Exemplo n.º 28
0
def main():
    G=nx.Graph()

    G.add_edge('a','b',weight=0.6)
    G.add_edge('a','c',weight=0.2)
    G.add_edge('c','d',weight=0.1)
    G.add_edge('c','e',weight=0.7)
    G.add_edge('c','f',weight=0.9)
    G.add_edge('a','d',weight=0.3)

    elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5]
    esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5]

    pos=nx.spring_layout(G) # positions for all nodes

# nodes
    nx.draw_networkx_nodes(G,pos,node_size=700)

# edges
    nx.draw_networkx_edges(G,pos,edgelist=elarge,width=6)
    nx.draw_networkx_edges(G,pos,edgelist=esmall,width=6,alpha=0.5,edge_color='b',style='dashed')

# labels
    nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif')

    plt.axis('off')
#plt.savefig("weighted_graph.png") # save as png
    plt.show() # display
    return
Exemplo n.º 29
0
def draw(inF):
    G = nx.Graph()

    inFile = open(inF)
    S = set()
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        for item in fields:
            S.add(item)
    inFile.close()

    L = list(S)
    G.add_nodes_from(L)

    LC = []
    for x in L:
        if x == 'EGR1' or x == 'RBM20':
            LC.append('r')
        else:
            LC.append('w')

    inFile = open(inF)
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        for i in range(len(fields)-1):
            G.add_edge(fields[i], fields[i+1])
    inFile.close()
    nx.draw_networkx(G,pos=nx.spring_layout(G), node_size=800, font_size=6, node_color=LC)
    limits=plt.axis('off')
    plt.savefig(inF + '.pdf')
Exemplo n.º 30
0
 def test_labels_and_colors(self):
     G = nx.cubical_graph()
     pos = nx.spring_layout(G)  # positions for all nodes
     # nodes
     nx.draw_networkx_nodes(G, pos,
                            nodelist=[0, 1, 2, 3],
                            node_color='r',
                            node_size=500,
                            alpha=0.8)
     nx.draw_networkx_nodes(G, pos,
                            nodelist=[4, 5, 6, 7],
                            node_color='b',
                            node_size=500,
                            alpha=0.8)
     # edges
     nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
     nx.draw_networkx_edges(G, pos,
                            edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
                            width=8, alpha=0.5, edge_color='r')
     nx.draw_networkx_edges(G, pos,
                            edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
                            width=8, alpha=0.5, edge_color='b')
     # some math labels
     labels = {}
     labels[0] = r'$a$'
     labels[1] = r'$b$'
     labels[2] = r'$c$'
     labels[3] = r'$d$'
     labels[4] = r'$\alpha$'
     labels[5] = r'$\beta$'
     labels[6] = r'$\gamma$'
     labels[7] = r'$\delta$'
     nx.draw_networkx_labels(G, pos, labels, font_size=16)
     plt.show()
Exemplo n.º 31
0
import matplotlib.pyplot as plt
import networkx as nx

G = nx.binomial_graph(10, 0.3, directed=True)
layout = nx.spring_layout(G)
plt.figure(1)
nx.draw(G, pos=layout, node_color='y')

pr = nx.pagerank(G, alpha=0.85)
print(pr)
for node, pageRankValue in pr.items():
    print("%d,%.4f" % (node, pageRankValue))

plt.figure(2)
nx.draw(G,
        pos=layout,
        node_size=[x * 6000 for x in pr.values()],
        node_color='m',
        with_labels=True)
plt.show()
Exemplo n.º 32
0
        ],
    ]

    for x in range(20):
        name = datasetNamesB[x][0]
        listTables.insert(
            'end', datasetNamesB[x][0]
        )  #If you want nodes without [cost] replace all file  datasetNamesB with datasetNamesA
        i = 0
        for y in datasetCost[x]:
            if y != -1:
                DG.add_weighted_edges_from([(name, datasetNamesB[i][0], y)],
                                           pos=(53.5672, 10.0285))
            i += 1

    pos = nx.spring_layout(DG)
    nx.draw_networkx_edge_labels(DG,
                                 pos,
                                 edge_labels=nx.get_edge_attributes(
                                     DG, 'weight'),
                                 font_color='red',
                                 ax=a)
    nx.draw_networkx(DG,
                     pos,
                     font_size=16,
                     with_labels=False,
                     edge_color='b',
                     ax=a)
    # for p in pos:  # raise text positions
    #     pos[p][1] += 0.07
    nx.draw_networkx_labels(DG, pos, font_size=10, ax=a)
Exemplo n.º 33
0
Gd = nx.davis_southern_women_graph()
Ad = AntiGraph(nx.complement(Gd))
Gk = nx.karate_club_graph()
Ak = AntiGraph(nx.complement(Gk))
pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)]
# test connected components
for G, A in pairs:
    gc = [set(c) for c in nx.connected_components(G)]
    ac = [set(c) for c in nx.connected_components(A)]
    for comp in ac:
        assert comp in gc
# test biconnected components
for G, A in pairs:
    gc = [set(c) for c in nx.biconnected_components(G)]
    ac = [set(c) for c in nx.biconnected_components(A)]
    for comp in ac:
        assert comp in gc
# test degree
for G, A in pairs:
    node = list(G.nodes())[0]
    nodes = list(G.nodes())[1:4]
    assert G.degree(node) == A.degree(node)
    assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
    # AntiGraph is a ThinGraph, so all the weights are 1
    assert sum(d for n, d in A.degree()) == sum(d for n, d in A.degree(weight="weight"))
    assert sum(d for n, d in G.degree(nodes)) == sum(d for n, d in A.degree(nodes))

pos = nx.spring_layout(G, seed=268)  # Seed for reproducible layout
nx.draw(Gnp, pos=pos)
plt.show()
Exemplo n.º 34
0
def draw_graph(G, size=7):
    global plot
    plt.figure(plot, (size, size))
    pos = nx.spring_layout(G)
    nx.draw_networkx(G, with_labels=True, pos=pos)
    plot += 1
Exemplo n.º 35
0
def choose_identifier_MST(attribute_1,path_dic_identifier,U):

    search_attribute_1=first_function(attribute_1,path_dic_identifier)
    sub_1=U.subgraph(search_attribute_1)

    labels={}
    for i in nx.nodes(sub_1):
        labels[i] = i

    plt.figure()

    pos = nx.spring_layout(U)

    nx.draw_networkx_nodes(U, pos, nodelist=search_attribute_1, node_color='b')
    nx.draw_networkx_nodes(U, pos, nodelist=list(set(nx.nodes(U))-set(search_attribute_1)), node_color='r')
    nx.draw_networkx_labels(U, pos, labels, font_size=10)
    nx.draw_networkx_edges(U, pos, edgelist=nx.edges(U))
    plt.axis('off')
    plt.legend((str(attribute_1),'others'))
  
    print("degree of",attribute_1,":")
    
    print("\n")
    
    degree_nodes=nx.degree(U)

    degree={}
    for i in labels.keys():
        degree[i]=degree_nodes[i]

    degree_nodes_sorted= sorted(degree,key=degree.get, reverse=True)

    for r in degree_nodes_sorted:
        print(r,degree[r])
            
    print("\n")
            
    print("betweeness centrality of",attribute_1,":")
    
    print("\n")
            
    centrality_nodes=nx.betweenness_centrality(U)
    
    centrality={}
    for i in labels.keys():
        centrality[i]=centrality_nodes[i]

    centrality_nodes_sorted= sorted(centrality,key=centrality.get, reverse=True)

    for r in centrality_nodes_sorted:
        print(r,centrality[r])

    print("\n")
    
    print ('graphical representation:')
            
    plt.figure()

    degree_nodes=nx.degree(U)
    centrality_nodes=nx.betweenness_centrality(U)
    x=list(degree_nodes.keys())
    z=list(centrality_nodes.values())
    y=list(degree_nodes.values())
    y_sort = sorted(y, key=int, reverse=False)
    fig, ax = plt.subplots(figsize=(30, 15)) 
    #ax1=plt.subplots()
    #ax2=ax1.twinx()
    ax.plot(x,y_sort, c='b')
    ax1=ax.twinx()
    #df.sort()
    ax1.plot(x,z, c='r')
    red_patch = mpatches.Patch(color='red', label='betweeness centrality')
    blue_patch = mpatches.Patch(color='blue', label='degree')
    plt.legend(handles=[red_patch, blue_patch])

    return(plt.show())
Exemplo n.º 36
0
    def graph(self):
       # from random import random
        IEfamilies = []
        IEs = []
        try:
            try:
                
                with open (self.minimapOut,'r') as file1:

                    for line in file1:

                        line = line.rstrip()
                        sp = line.split('\t')
                        query1 = sp[0].split('_')
                        coords1 = query1[3].split('-')
                        starta = coords1[0]
                        stopa = coords1[1]
                        length1 = int(stopa) - int(starta)
#                        query2 = sp[1].split('_')
#                        coords2 = query2[3].split('-')
#                        startb = coords2[0]
#                        stopb = coords2[1]
#                        length2 = int(stopb) - int(startb)
#                            print(float(int(sp[3])/length1))
                        if length1 > 0:
                            if float(int(sp[3])/length1) > 0.8:
                                with open('./Data_{0}/final_introns.tsv'.format(self.NAME), 'a') as file2:
                                    file2.write('{0}\n'.format(line))
#                            else:
#                                
#                                if float(int(sp[3])/length1) > 0.7:
#                                    with open('./Data_{0}/final_introns.tsv'.format(self.NAME), 'a') as file2:
#                                        file2.write('{0}\n'.format(line))
#                        else:
#                            print(float(int(sp[3])/length2))
#                            if length2 > 180:
#                                if float(int(sp[3])/length2) > 0.6:
#                                    with open('./Data_{0}/final_introns.tsv'.format(self.NAME), 'a') as file2:
#                                        file2.write('{0}\n'.format(line))       
#                            else:
#                                if float(int(sp[3])/length2) > 0.7:
#                                    with open('./Data_{0}/final_introns.tsv'.format(self.NAME), 'a') as file2:
#                                        file2.write('{0}\n'.format(line))
                
                data = pd.read_csv('./Data_{0}/final_introns.tsv'.format(self.NAME), sep='\t', header=None)
                df = nx.from_pandas_edgelist(data, source=0, target=1, edge_attr=True)
                
                
                communities_generator = community.girvan_newman(df)
                top_level_communities = next(communities_generator)
                IEfam = sorted(map(sorted, top_level_communities))
                for fam in IEfam:
                    if len(fam) > 5:
                        IEfamilies.append(fam)
                    else:
                        IEs = IEs + fam
                for fam in IEs:
                    df.remove_node(fam)
                print(len(IEfamilies))
                pos = nx.spring_layout(df)
                plt.figure(figsize=(20,20))
               # colors = [(random(), random(), random()) for _i in range(10)]
                nx.draw_networkx(df, pos, with_labels=False) 
                #plt.title('{0}'.format(self.NAME))
                
                #print(IEfamilies)
                colorListTwo = ['Red',
                                'Lime',
                                'Blue',
                                'Yellow',
                                'Cyan',
                                'Magenta',
                                'Maroon',
                                'Olive',
                                'Green',
                                'Purple',
                                'Teal',
                                'Navy', 
                                'darkgoldenrod', 
                                'cadetblue', 
                                'aqua', 
                                'darkseagreen',
                                'lightblue', 
                                'deeppink',
                                'mediumslateblue',
                                'gold',
                                'coral',
                                'slategrey',
                                'indigo',
                                'lawngreen',
                                'beige',
                                'rosybrown',
                                'mediumspringgreen',
                                'mediumblue',
                                'orchid',
                                'aliceblue',
                                'darkmagenta',
                                'darkseagreen',
                                'limegreen',
                                'powderblue',
                                'whitesmoke',
                                'navajowhite',
                                'oldlace',
                                'mediumpurple',
                                'mediumturquoise',
                                'peru',
                                'plum',
                                'wheat',
                                'thistle',
                                'sienna',
                                'linen',
                                'lemonchiffon',
                                'khaki',
                                'darkorchid',
                                'cornsilk',
                                'cadetblue'
                                ]
                count = 0
                for fam in IEfamilies:
                   # print(fam)
                    nx.draw_networkx_nodes(df, pos, with_labels=False, nodelist = fam, node_color = colorListTwo[count])
                    count += 1
                    
                    
                os.system("rm -r ./Data_{0}/final_introns.tsv".format(self.NAME))
                plt.savefig('./Data_{0}/Blast_fig.png'.format(self.NAME))
            except EmptyDataError:
                pass
        except NameError:
            IEfamilies = 'None'

        return IEfamilies
def draw_graph(G):
    pos = nx.spring_layout(G)
    nx.draw_networkx_nodes(G, pos,cluster_0, node_color='r')
    nx.draw_networkx_nodes(G, pos,cluster_1, node_color='b')
    nx.draw_networkx_labels(G, pos,font_size=10)
    nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
Exemplo n.º 38
0
def drawjrsr(jrsrpeers, jrsrnodes, jrsredges, jrsrdevnodes):
    usernodes = list()
    useredges = list()
    useredegestemp = set()
    JRSRG = nx.MultiGraph()
    JRSRG.add_edges_from(jrsrpeers)  #所有节点和边都从这里进入图,对节点和边的操作是与节点和边为索引对应的。

    usernodes = list(set(JRSRG.nodes()) -
                     jrsrnodes)  #分离出用户节点。这些工作可以在上一个数据库处理函数里完成。
    #for n in usernodes:
    #    print n,
    for ed in set(jrsrpeers):  #分离局与局间的连线和用户与局之间连线。
        useredegestemp.add(ed)
    useredges = list(useredegestemp - jrsredges)

    #useredges = list(set(JRSRG.edges())-jrsredges)

    pos = nx.spring_layout(JRSRG)

    nx.draw_networkx_nodes(JRSRG,
                           pos,
                           list(jrsrnodes),
                           node_color='g',
                           node_size=3000,
                           alpha=0.5,
                           node_shape='s')  #操作局节点颜色和形状大小。shape=>'o':圆,'s':方。
    nx.draw_networkx_nodes(JRSRG,
                           pos,
                           usernodes,
                           node_color='y',
                           node_size=2000,
                           alpha=1,
                           node_shape='o')  #操作用户节点颜色和形状大小。shape=>'o':圆,'s':方。
    nx.draw_networkx_nodes(
        JRSRG,
        pos,
        list(jrsrdevnodes),
        node_color='b',
        node_size=1000,
        alpha=0.5,
        node_shape='o')  #在有设备的节点上加画节点颜色和大小。shape=>'o':圆,'s':方。

    nx.draw_networkx_edges(JRSRG, pos, width=1.0, alpha=0.5)  #缺省画的细边。
    nx.draw_networkx_edges(JRSRG,
                           pos,
                           list(jrsredges),
                           width=8,
                           alpha=0.5,
                           edge_color='r')  #局间的边,加画红色。
    nx.draw_networkx_edges(JRSRG,
                           pos,
                           useredges,
                           width=8,
                           alpha=0.4,
                           edge_color='b')  #用户到局的边,加画蓝色。
    '''
    nx.draw_networkx_nodes(JRSRG,pos,node_color='g',node_shape='s',alpha=0.5,node_size=3000) # shape=>'o':圆,'s':方.
    nx.draw_networkx_edges(JRSRG,pos,alpha=0.5,width=6)
    '''
    #font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=15)
    nx.draw_networkx_labels(JRSRG,
                            pos,
                            font_size=15,
                            font_weight='bold',
                            font_family='sans-serif')

    #plt.title(jrsrname)
    #nx.draw(JRSRG)
    plt.show()
Exemplo n.º 39
0
g.add_edge("Hillary", "Clinton")
g.add_edge("Trump", "Ivanka")
g.add_edge("Trump", "Clinton")
g.add_edge("Obama", "Mitt")

g.add_edges_from([("Hillary", "Clinton"), ("Obama", "Trump"),
                  ("Obama", "Clinton"), ("Michelle", "Mitt")])

g.nodes()
g.edges()

nx.info(g)
nx.draw(g)

nx.draw(g, with_labels=True)
nx.draw_networkx(g)

nx.spring_layout(g)

nx.degree(g, "Trump")
nx.degree(g, "Obama")
nx.degree(g, "Clinton")

print(nx.degree_centrality(g))
nx.eigenvector_centrality(g)
print(nx.eigenvector_centrality(g))

nx.betweenness_centrality(g)
print(nx.betweenness_centrality(g))

plt.show()
Exemplo n.º 40
0
            node_colors.append(cols[0])
        elif (i[1] == levels[1]):
            node_colors.append(cols[1])
        elif (i[1] == levels[2]):
            node_colors.append(cols[2])
        else:
            node_colors.append(cols[3])
        """
print(levels)    
print(node_colors)
print(node_centre)
sorted_node_centre
 """

#labels of edges
pos = nx.spring_layout(g)
nx.draw(g, pos, node_color=node_colors, node_size=900, with_labels=True)
labels = nx.get_edge_attributes(g, 'weight')
nx.draw_networkx_edge_labels(g, pos, edge_labels=labels)
plt.savefig("degree centrality")
print("///////////DEGREE CENTRALITY////////////")
print(g.degree(g.nodes))
plt.show()  #degree centrality

closness = []
close_colors = []
for node in node_centre:

    closness.append((node[0], nx.closeness_centrality(g, node[0], 'weight')))

sorted_node_close = sorted(closness, key=itemgetter(1), reverse=True)
Exemplo n.º 41
0
def graphNetwork(edgesfile,
                 nodesfile,
                 layout='spring',
                 graphfile='network_grpah.png',
                 title="",
                 show_labels=False,
                 constant_node_size=False):
    import networkx as nx
    import matplotlib.pyplot as plt
    import pandas as pd
    # Declare graph object
    G = nx.Graph()
    # Read network data
    inputedges = pd.read_csv(edgesfile)
    inputnodes = pd.read_csv(nodesfile)
    node_sizes = []
    node_colours = []
    node_labels = []
    for i, r in inputnodes.iterrows():
        if r['college_code'] == "DSC":
            G.add_node(r['ID'],
                       color='red',
                       size=r['student_pop'],
                       label='DSC')
        elif r['college_code'] == "BUS":
            G.add_node(r['ID'],
                       color='blue',
                       size=r['student_pop'],
                       label='BUS')
        elif r['college_code'] == "SEH":
            G.add_node(r['ID'],
                       color='green',
                       size=r['student_pop'],
                       label='SEH')
        else:
            G.add_node(r['ID'],
                       color='black',
                       size=r['student_pop'],
                       label='NA')

        node_labels.append(r['ID'])

    for i, r in inputedges.iterrows():
        #if r['Weight'] > 300:
        #    G.add_edge(r['Source'], r['Target'], weight=int(300))
        #else:
        G.add_edge(r['Source'], r['Target'], weight=int(r['Weight']))

    # assign layout
    if layout == 'shell':
        pos = nx.shell_layout(G)
    elif layout == 'spectral':
        pos = nx.spectral_layout(G)
    elif layout == 'random':
        pos = nx.random_layout(G)
    else:
        pos = nx.spring_layout(G, iterations=200, scale=5000)

    # set nodes to positions
    nx.set_node_attributes(G, 'pos', pos)

    try:
        color_map = []
        size_map = []
        edge_colors = []
        for n in G.nodes():
            color_map.append(G.node[n]['color'])
            size_map.append(G.node[n]['size'])

        for e in G.edges(data=True):
            edge_colors.append(e[2]['weight'])

        labels = {k: k for k in node_labels}
        plt.figure(figsize=(12.0, 9.0))
        plt.title(title)
        if constant_node_size:
            nodes = nx.draw_networkx_nodes(G,
                                           pos=pos,
                                           labels=labels,
                                           node_size=8,
                                           node_color=color_map)
        else:
            nodes = nx.draw_networkx_nodes(G,
                                           pos=pos,
                                           labels=labels,
                                           node_size=size_map,
                                           node_color=color_map)
        edges = nx.draw_networkx_edges(G,
                                       pos=pos,
                                       edge_color=edge_colors,
                                       edge_cmap=plt.cm.copper_r)
        plt.colorbar(edges)
        plt.axis('off')
        if show_labels:
            nx.draw_networkx_labels(G, pos, labels, font_size=12)

        print "Nodes:\t%i" % G.number_of_nodes()
        print "Edges:\t%i" % G.number_of_edges()

        plt.savefig(graphfile, dpi=500)
        plt.clf()
        plt.close()

    except Exception as e:
        print e
        pass
Exemplo n.º 42
0
def genesis(G, arguments):

    pylab.ion()

    # input params
    N = int(arguments['N'])
    E = int(arguments['E'])
    M = int(arguments['M'])
    alpha = float(arguments['alpha'])
    generations = int(arguments['gens'])

    node_positions = nx.spring_layout(G)

    #(***)
    for t in range(1, generations + 1):

        N = len(G.nodes())
        E = len(G.edges())

        G, node_positions = evolve(G, N, E, M, alpha, t, node_positions)

        if GRAPHICS and not PYLAB:
            nx.draw_networkx_nodes(G,
                                   pos=node_positions,
                                   node_color='grey',
                                   label=True,
                                   node_size=200)
            nx.draw_networkx_edges(G,
                                   pos=node_positions,
                                   edge_color='grey',
                                   label=True)
            nx.draw_networkx_labels(G, pos=node_positions, font_size=10)
            plt.show()
            pause(FRAMERATE * 0.00066)

        if DEBUG:
            print(color.GREEN + "finished evolution: " + str(t))

        if GRAPHICS and PYLAB:
            graph = get_graph(G, node_positions)
            graph.canvas.draw()
            pylab.draw()
            pause(0.5)
            pylab.close(graph)

        if DEBUG:
            print(color.RED + color.BOLD + "at time " + str(t) + ": ")

        if DEBUG and False:
            a = open("error_log_after_evolve.txt", "w")

            a.write(str(node_positions) + "\n")
            a.write(str(G.nodes()) + "\n \n" + str(G.edges()))
            a.close()

        if DEBUG and False:
            f = open("error_log_before_evolve.txt", "w")

            f.write(str(node_positions) + "\n")
            f.write(str(G.nodes()) + "\n \n" + str(G.edges()))
            f.close()

        if DEBUG:
            print(color.GREEN + "finished generation: " + str(t))

    else:
        print(G)

    if False:
        print(color.RED + "Node " + color.BOLD + str(n) + " added at time " +
              color.BLUE + str(t) + color.END)
        print(color.GREEN + color.BOLD + "local(n)" + color.END + ": " +
              str(local_world))
Exemplo n.º 43
0
def create_graph(input_path, input_file, output_path, output_file, min_freq):
    
    # Create empty graph:

    G = nx.Graph()

    # Populate the graph with the keywords/clusters as nodes:
    
    id_response = ""
    keyword_nodes = list()
    kw2response = dict() # maps a kw to the list of responses containing it

    with open(os.path.join(input_path, input_file), 'rb') as csv_file:
        next(csv_file)
        res_reader = csv.reader(csv_file, delimiter=',')
        my_count = 0
        for row in res_reader:
            id_response = row[0]
            kw = row[2]
            keyword_nodes.append(kw)
            if kw in kw2response:
                responses_for_kw = kw2response[kw]
                responses_for_kw.append(id_response)
                kw2response[kw] = responses_for_kw
            else:
                kw2response[kw] = [id_response]
            
    
    keyword_nodes = list(set(keyword_nodes))
    keyword_nodes.sort()
    
    # only keep keywords that occur in more than min_response response:
    for kw in keyword_nodes:
        if len(kw2response[kw]) < min_freq + 1:
            keyword_nodes.remove(kw)
    
    
    for kw in keyword_nodes:
        G.add_node(kw)
    #print(str(G.nodes()))
    
    # Add edges to graph:
    
    # two nodes (keywords) are connected if they appear in the same response:
    for kw1 in keyword_nodes:
        responses_kw1 = kw2response[kw1]
        for kw2 in keyword_nodes:
            responses_kw2 = kw2response[kw2]
            overlap = len(list(set(responses_kw1).intersection(responses_kw2)))
            if overlap > 0:
                G.add_edge(kw1, kw2, weight = overlap^2)
            
    #print(str(G.edges()))
    
    # Plot graph:
    
    pos = nx.spring_layout(G) # positions for all nodes
    edges = G.edges()
    weights = [G[u][v]['weight'] for u,v in edges]

    nx.draw(G, pos, edges = edges, width=weights, with_labels = True)
    #plt.show()
    plt.savefig(os.path.join(output_path, output_file))        
Exemplo n.º 44
0
def choose_identifier(attribute_1,attribute_2,path_dic_identifier,U_degree6,):

    search_attribute_1=first_function(attribute_1,path_dic_identifier)
    sub_1=U_degree6.subgraph(search_attribute_1)
    path_dic_identifier_new = {k: path_dic_identifier[k] for k in search_attribute_1}
    search_attribute_2=first_function(attribute_2,path_dic_identifier_new)
    sub_2=U_degree6.subgraph(search_attribute_2)
    sub=nx.nodes(sub_1)+nx.nodes(sub_2)
    sub_new=U_degree6.subgraph(sub)

    labels={}
    for i in nx.nodes(sub_new):
        labels[i] = i

    plt.figure()

    pos = nx.spring_layout(sub_new)

    nx.draw_networkx_nodes(sub_new, pos, nodelist=search_attribute_1, node_color='r')
    nx.draw_networkx_nodes(sub_new, pos, search_attribute_2, node_color='b')
    nx.draw_networkx_labels(sub_new, pos, labels, font_size=10)
    nx.draw_networkx_edges(sub_new, pos, edgelist=nx.edges(sub_new))
    plt.legend((str(attribute_1),str(attribute_2)))
    plt.axis('off')
    plt.show()
  
    degree_nodes=nx.degree(sub_new)

    degree_nodes_sorted= sorted(degree_nodes,key=degree_nodes.get, reverse=True)

    print ('degree:')
    
    print("\n")
    
    for r in degree_nodes_sorted:
        print(r,degree_nodes[r])
            
    centrality_nodes=nx.betweenness_centrality(sub_new)

    centrality_nodes_sorted= sorted(centrality_nodes,key=centrality_nodes.get, reverse=True)

    print("\n")
    
    print ('betweeness centrality:')
    
    print("\n")
    
    for r in centrality_nodes_sorted:
        
        print(r,centrality_nodes[r])

    print("\n")
    
    print ('graphical representation:')
            
    plt.figure()

    degree_nodes=nx.degree(sub_new)
    centrality_nodes=nx.betweenness_centrality(sub_new)
    x=list(degree_nodes.keys())
    z=list(centrality_nodes.values())
    y=list(degree_nodes.values())
    y_sort = sorted(y, key=int, reverse=False)
    fig, ax = plt.subplots(figsize=(20, 10)) 
    #ax1=plt.subplots()
    #ax2=ax1.twinx()
    ax.plot(x,y_sort, c='b')
    ax1=ax.twinx()
    #df.sort()
    ax1.plot(x,z, c='r')
    red_patch = mpatches.Patch(color='red', label='betweeness centrality')
    blue_patch = mpatches.Patch(color='blue', label='degree')
    plt.legend(handles=[red_patch, blue_patch])

    return(plt.show())
def main():

    G = nx.Graph()
    pos = nx.spring_layout(G)

    ####################################################################################################

    # nodes (territories) separated by their region on the board

    # Arnor
    arnor_nodes = [
        "Angmar", "Borderlands", "Buckland", "Eastern Angmar", "Fornost",
        "Forodwaith", "North Downs", "Old Forest", "Rhudaur", "South Downs",
        "Weather Hills"
    ]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=arnor_nodes,
                           node_color='black',
                           node_size=500,
                           alpha=0.8)

    # Rhovanion
    rhovanion_nodes = [
        "Brown Lands", "Dead Marshes", "Emyn Muil", "Gladden Fields", "Lorien",
        "Moria", "Rhun Hills", "The Wold"
    ]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=rhovanion_nodes,
                           node_color='grey',
                           node_size=500,
                           alpha=0.8)

    # Rohan
    rohan_nodes = [
        "Dunland", "Enedwaith", "Eregion", "Fangorn", "Gap of Rohan",
        "Minhiriath", "West Rohan"
    ]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=rohan_nodes,
                           node_color='brown',
                           node_size=500,
                           alpha=0.8)

    # Mirkwood
    mirkwood_nodes = [
        "Anduin Valley", "Carrock", "Eastern Mirkwood", "North Mirkwood",
        "South Mirkwood"
    ]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=mirkwood_nodes,
                           node_color='red',
                           node_size=500,
                           alpha=0.8)

    # Eriador
    eriador_nodes = [
        "Evendim Hills", "Forlindon", "Harlindon", "Lune Valley", "Mithlond",
        "The Shire", "Tower Hills"
    ]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=eriador_nodes,
                           node_color='darkorange',
                           node_size=500,
                           alpha=0.8)

    # Rhun
    rhun_nodes = ["Esgaroth", "North Rhun", "South Rhun", "Weathered Heath"]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=rhun_nodes,
                           node_color='yellow',
                           node_size=500,
                           alpha=0.8)

    # Gondor
    gondor_nodes = [
        "Andrast", "Anfalas", "Belfalas", "Druwaith Iaur", "Ithilien",
        "Lamedon", "Lebennin", "Minas Tirith", "South Ithilien",
        "Vale of Erech"
    ]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=gondor_nodes,
                           node_color='seagreen',
                           node_size=500,
                           alpha=0.8)

    # Mordor
    mordor_nodes = [
        "Barad-dur", "Gorgoroth", "Minas Morgul", "Mount Doom", "Nurn",
        "Udun Vale"
    ]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=mordor_nodes,
                           node_color='deeppink',
                           node_size=500,
                           alpha=0.8)

    # Haradwaith
    haradwaith_nodes = [
        "Deep Harad", "Harad", "Harondor", "Khand", "Near Harad", "Umbar"
    ]
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=haradwaith_nodes,
                           node_color='blue',
                           node_size=500,
                           alpha=0.8)

    ####################################################################################################

    # edges (borders) on the board

    # self-contained edges, i.e. edges that are between two nodes in the same region

    # Arnor
    edges_1 = [("Eastern Angmar", "Forodwaith"), ("Forodwaith", "Angmar"),
               ("Forodwaith", "Borderlands"), ("Angmar", "Borderlands"),
               ("Borderlands", "North Downs"), ("Borderlands", "Fornost"),
               ("Borderlands", "Weather Hills"), ("North Downs", "Fornost"),
               ("Fornost", "Buckland"), ("Fornost", "Old Forest"),
               ("Fornost", "Weather Hills"), ("Buckland", "Old Forest"),
               ("Buckland", "South Downs"), ("Old Forest", "South Downs"),
               ("Old Forest", "Weather Hills"),
               ("Weather Hills", "South Downs"), ("Weather Hills", "Rhudaur")]

    # Rhovanion
    edges_2 = [("Moria", "Gladden Fields"), ("Gladden Fields", "Lorien"),
               ("Lorien", "The Wold"), ("The Wold", "Emyn Muil"),
               ("Emyn Muil", "Dead Marshes"), ("Emyn Muil", "Brown Lands"),
               ("Brown Lands", "Dead Marshes"), ("Brown Lands", "Rhun Hills")]

    # Rohan
    edges_3 = [("Eregion", "Dunland"), ("Dunland", "Minhiriath"),
               ("Dunland", "Enedwaith"), ("Enedwaith", "Minhiriath"),
               ("Enedwaith", "Gap of Rohan"), ("Gap of Rohan", "West Rohan"),
               ("Gap of Rohan", "Fangorn")]

    # Mirkwood
    edges_4 = [("Carrock", "North Mirkwood"), ("Carrock", "Anduin Valley"),
               ("North Mirkwood", "Eastern Mirkwood"),
               ("Eastern Mirkwood", "Anduin Valley"),
               ("Eastern Mirkwood", "South Mirkwood"),
               ("South Mirkwood", "Anduin Valley")]

    # Eriador
    edges_5 = [("Forlindon", "Mithlond"), ("Mithlond", "Lune Valley"),
               ("Mithlond", "Tower Hills"), ("Mithlond", "Harlindon"),
               ("Lune Valley", "Evendim Hills"),
               ("Lune Valley", "Tower Hills"),
               ("Evendim Hills", "Tower Hills"), ("Tower Hills", "The Shire")]

    # Rhun
    edges_6 = [("North Rhun", "Weathered Heath"), ("North Rhun", "South Rhun"),
               ("Weathered Heath", "Esgaroth")]

    # Gondor
    edges_7 = [("Druwaith Iaur", "Anfalas"), ("Anfalas", "Andrast"),
               ("Anfalas", "Vale of Erech"), ("Vale of Erech", "Lamedon"),
               ("Lamedon", "Belfalas"), ("Lamedon", "Lebennin"),
               ("Lebennin", "Belfalas"), ("Lebennin", "Minas Tirith"),
               ("Minas Tirith", "Ithilien"), ("Ithilien", "South Ithilien")]

    # Mordor
    edges_8 = [("Udun Vale", "Mount Doom"), ("Mount Doom", "Barad-dur"),
               ("Mount Doom", "Gorgoroth"), ("Gorgoroth", "Barad-dur"),
               ("Gorgoroth", "Minas Morgul"), ("Gorgoroth", "Nurn")]

    # Haradwaith
    edges_9 = [("Harondor", "Harad"), ("Harad", "Deep Harad"),
               ("Harad", "Near Harad"), ("Deep Harad", "Umbar"),
               ("Near Harad", "Khand")]

    # edges between different nodes (territories) in different regions

    edges_misc = [("Forodwaith", "Mithlond"), ("Forodwaith", "North Rhun"),
                  ("Forodwaith", "Weathered Heath"),
                  ("Eastern Angmar", "Carrock"),
                  ("Borderlands", "Lune Valley"),
                  ("Borderlands", "Evendim Hills"), ("Buckland", "The Shire"),
                  ("South Downs", "Minhiriath"), ("Rhudaur", "Eregion"),
                  ("Rhudaur", "Carrock"), ("Moria", "Eregion"),
                  ("Gladden Fields", "Anduin Valley"), ("Lorien", "Fangorn"),
                  ("The Wold", "Fangorn"), ("The Wold", "Gap of Rohan"),
                  ("Emyn Muil", "Anduin Valley"),
                  ("Emyn Muil", "South Mirkwood"),
                  ("Brown Lands", "South Mirkwood"),
                  ("Brown Lands", "Eastern Mirkwood"),
                  ("Brown Lands", "South Rhun"), ("Dead Marshes", "Ithilien"),
                  ("Dead Marshes", "Udun Vale"), ("Minhiriath", "Mithlond"),
                  ("Minhiriath", "Belfalas"), ("Minhiriath", "Umbar"),
                  ("West Rohan", "Druwaith Iaur"),
                  ("Gap of Rohan", "Minas Tirith"),
                  ("North Mirkwood", "Esgaroth"), ("Ithilien", "Minas Morgul"),
                  ("South Ithilien", "Harondor"), ("Belfalas", "Umbar")]

    # all of the edges in the game
    all_edges = edges_1 + edges_2 + edges_3 + edges_4 + edges_5 + edges_6 + edges_7 + edges_8 + edges_9 + edges_misc

    nx.draw_networkx_edges(G, pos, edgelist=all_edges, width=8, alpha=0.5)

    ####################################################################################################

    # show the graph of the game

    nx.draw_kamada_kawai(G)
    plt.show()
Exemplo n.º 46
0
        print('clee', clee)  # clee
        print('valeur', clee)  # value
        for cle, valeur in clee.items():
            print('valeur', valeur)
            print('cle', cle)

G = nx.DiGraph()

G.add_edges_from([('A', 'B')], weight=2)
G.add_edges_from([('D', 'E'), ('E', 'F'), ('G', 'H')], weight=3)
G.add_edges_from([('B', 'E'), ('C', 'E'), ('E', 'G')], weight=4)
G.add_edges_from([('A', 'D'), ('D', 'F'), ('F', 'H')], weight=5)
G.add_edges_from([('C', 'G')], weight=6)
G.add_edges_from([('A', 'E')], weight=7)
G.add_edges_from([('C', 'G')], weight=9)

edge_labels = dict([((u, v,), d['weight'])
                    for u, v, d in G.edges(data=True)])
red_edges = [('C', 'D'), ('D', 'A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]

pos = nx.spring_layout(G)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw_networkx(G, pos, node_size=2500, edge_color=edge_colors, edge_cmap=plt.cm.Reds)
# pylab.show()
"""
Réponse :
Plus court chemin ex3 :  ['e', 'c', 'f', 's']  de longueur : 10
Plus court chemin ex4 :  ['a', 'b', 'e', 'g', 'h']  de longueur : 13
"""
Exemplo n.º 47
0
    def network(self, figsize=(14, 9), fig=True):
        """
        Display information about the container's object relationships.

        Nodes correspond to data objects. The size of the node corresponds
        to the size of the table in memory. The color of the node corresponds
        to its fundamental data type. Nodes are labeled by their container
        name; class information is listed below. The color of the connections
        correspond to the type of relationship; either an index of one table
        corresponds to a column in another table or the two tables share an
        index.

        Args:
            figsize (tuple): Tuple containing figure dimensions
            fig (bool): Generate the figure (default true)

        Returns:
            graph: Network graph object containing data relationships
        """
        conn_types = ['index-index', 'index-column']
        conn_colors = mpl.sns.color_palette('viridis', len(conn_types))
        conn = dict(zip(conn_types, conn_colors))

        def get_node_type_color(obj):
            """Gets the color of a node based on the node's (sub)type."""
            cols = mpl.sns.color_palette('viridis', len(conn_types))
            for col in cols:
                if isinstance(obj, (pd.DataFrame, pd.Series, pd.SparseSeries,
                                    pd.SparseDataFrame)):
                    typ = type(obj)
                    return '.'.join((typ.__module__, typ.__name__)), col
            return 'other', 'gray'

        def legend(items, name, loc, ax):
            """Legend creation helper function."""
            proxies = []
            descriptions = []
            for label, color in items:
                if label == 'column-index':
                    continue
                if name == 'Data Type':
                    line = mpl.sns.mpl.lines.Line2D([], [],
                                                    linestyle='none',
                                                    color=color,
                                                    marker='o')
                else:
                    line = mpl.sns.mpl.lines.Line2D([], [],
                                                    linestyle='-',
                                                    color=color)
                proxies.append(line)
                descriptions.append(label)
            lgnd = ax.legend(proxies,
                             descriptions,
                             title=name,
                             loc=loc,
                             frameon=True)
            lgnd_frame = lgnd.get_frame()
            lgnd_frame.set_facecolor('white')
            lgnd_frame.set_edgecolor('black')
            return lgnd, ax

        info = self.info()
        info = info[info['type'] != '-']
        info['size'] *= 13000 / info['size'].max()
        info['size'] += 2000
        node_size_dict = info['size'].to_dict()  # Can pull all nodes from keys
        node_class_name_dict = info['type'].to_dict()
        node_type_dict = {}  # Values are tuple of "underlying" type and color
        node_conn_dict = {}  # Values are tuple of connection type and color
        items = self._data().items()
        for k0, v0 in items:
            n0 = k0[1:] if k0.startswith('_') else k0
            node_type_dict[n0] = get_node_type_color(v0)
            for k1, v1 in items:
                if v0 is v1:
                    continue
                n1 = k1[1:] if k1.startswith('_') else k1
                for name in v0.index.names:  # Check the index of data object 0 against the index
                    if name is None:  # and columns of data object 1
                        continue
                    if name in v1.index.names:
                        contyp = 'index-index'
                        node_conn_dict[(n0, n1)] = (contyp, conn[contyp])
                        node_conn_dict[(n1, n0)] = (contyp, conn[contyp])
                    for col in v1.columns:
                        # Catches index "atom", column "atom1"; does not catch atom10
                        if name == col or (name == col[:-1]
                                           and col[-1].isdigit()):
                            contyp = 'index-column'
                            node_conn_dict[(n0, n1)] = (contyp, conn[contyp])
                            node_conn_dict[(n1, n0)] = ('column-index',
                                                        conn[contyp])
        g = nx.Graph()
        g.add_nodes_from(node_size_dict.keys())
        g.add_edges_from(node_conn_dict.keys())
        node_sizes = [node_size_dict[node] for node in g.nodes()]
        node_labels = {
            node: ' {}\n({})'.format(node, node_class_name_dict[node])
            for node in g.nodes()
        }
        node_colors = [node_type_dict[node][1] for node in g.nodes()]
        edge_colors = [node_conn_dict[edge][1] for edge in g.edges()]
        # Build the figure and legends
        if fig:
            fig, ax = plt.subplots(1, figsize=figsize)
            ax.axis('off')
            pos = nx.spring_layout(g)
            nx.draw_networkx_nodes(g,
                                   pos=pos,
                                   ax=ax,
                                   alpha=0.7,
                                   node_size=node_sizes,
                                   node_color=node_colors)
            nx.draw_networkx_labels(g,
                                    pos=pos,
                                    labels=node_labels,
                                    font_size=17,
                                    font_weight='bold',
                                    ax=ax)
            nx.draw_networkx_edges(g,
                                   pos=pos,
                                   edge_color=edge_colors,
                                   width=2,
                                   ax=ax)
            l1, ax = legend(set(node_conn_dict.values()), 'Connection', (1, 0),
                            ax)
            _, ax = legend(set(node_type_dict.values()), 'Data Type', (1, 0.3),
                           ax)
            fig.gca().add_artist(l1)
        g.edge_types = {
            node: value[0]
            for node, value in node_conn_dict.items()
        }  # Attached connection information to network graph
        return g
Exemplo n.º 48
0
print(seen_lemma)

labels = {}
keys = list(seen_lemma.keys())

for i in range(len(seen_lemma)):
    labels[i] = keys[i][0].lower()

labels

#%matplotlib inline
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(9, 9))
pos = nx.spring_layout(lemma_graph)

nx.draw(lemma_graph, pos=pos, with_labels=False, font_weight="bold")
nx.draw_networkx_labels(lemma_graph, pos, labels)

ranks = nx.pagerank(lemma_graph)
ranks

for node_id, rank in sorted(ranks.items(), key=lambda x: x[1], reverse=True):
    print(node_id, rank, labels[node_id])


def collect_phrases(chunk, phrases, counts):
    chunk_len = chunk.end - chunk.start + 1
    sq_sum_rank = 0.0
    non_lemma = 0
'''
Draw Facebook Ego Network Using SNAP dataset and using NetworkX Library
'''

import networkx as nx
import matplotlib.pyplot as plt

g = nx.read_edgelist('facebook_combined.txt',
                     create_using=nx.Graph(),
                     nodetype=int)

print(nx.info(g))

sp = nx.spring_layout(g)

plt.axis('off')

nx.draw_networkx(g, pos=sp, with_labels=False, node_size=35)

plt.show()
Exemplo n.º 50
0
    #plt.show()


if __name__ == '__main__':

    config_parser.read(config_file)
    graph_name = config_parser.get('TOPO', 'topoloogy')
    graph_path = '../annotated_topo/' + graph_name + '.graphml'

    #print graph_path
    caps = json.loads(config_parser.get('CONSTRAINTS', 'linkbandwidth'))

    G = nx.read_graphml(graph_path, node_type=int)

    pos = nx.spring_layout(G)  # positions for all nodes
    #print pos
    rstPath = config_parser.get('PATHS', 'resultpath')

    for cap in caps:
        file_path = '../placement_alg/' + rstPath + str(
            cap) + '/' + graph_name + '/'
        affinix = 'fl'

        save_name = '../graphes/' + graph_name + '_' + str(cap) + '.pdf'
        #print save_name

        plot(G, pos, graph_name, file_path, affinix, save_name)

    rst_directory = '../placement_alg/' + rstPath
Exemplo n.º 51
0
def thanks():
    if request.args:
        id = request.args['id']
        f = open('post_comment.txt', 'w')
        try:
            offsets = [0, 20]
            for off in offsets:
                stroka1 = 'https://api.vk.com/method/wall.get?owner_id=' + str(
                    id
                ) + '&count=20&v=5.73&access_token=4e4390334e4390334e439033504e21bc6044e434e4390331552d00d82502b3b1e852732&offset=' + str(
                    off)
                req = urllib.request.Request(stroka1)
                response = urllib.request.urlopen(req)
                result = response.read().decode('utf-8')
                #print(result)
                if off == 0:
                    data = json.loads(result)
                else:
                    data1 = json.loads(result)
                    needed_data = data1['response']['items']
                    for n in needed_data:
                        data['response']['items'].append(n)
            #print(len(data['response']['items']))
            #print(type(data))
            for m in range(39):
                f.write(data["response"]["items"][m]["text"])
                f.write('\n')
                post = data["response"]["items"][m]["id"]
                for off in offsets:
                    stroka = 'https://api.vk.com/method/wall.getComments?owner_id=' + str(
                        id
                    ) + '&access_token=4e4390334e4390334e439033504e21bc6044e434e4390331552d00d82502b3b1e852732&post_id=' + str(
                        post) + '&count=100&v=5.73&offset=' + str(off)
                    requ = urllib.request.Request(stroka)
                    response1 = urllib.request.urlopen(requ)
                    result1 = response1.read().decode('utf-8')
                    if off == 0:
                        data2 = json.loads(result1)
                        for r in range(len(data2['response']['items'])):
                            f.write(data2['response']['items'][r]['text'])
                            f.write('\n')
                    else:
                        data3 = json.loads(result1)
                        for z in range(len(data3['response']['items'])):
                            f.write(data3['response']['items'][z]['text'])
                            f.write('\n')
                        #print(data3)
            f.close()
        except KeyError:
            return render_template('wrong.html')
        m = open('post_comment.txt', 'r')
        m = m.read()
        m = m.replace('!', '.')
        m = m.replace('?', '.')
        m = m.replace('\n', '.')
        m = m.lower()
        m = m.split('.')
        regPunct = re.compile('[^\w]*$', re.DOTALL)
        regOther = re.compile('[a-zA-Z0-9_#;,\>%&/\№|=\{\}:\.\[\]"\?\(\)\@«»]',
                              re.DOTALL)
        regTire = re.compile(' — ', re.DOTALL)
        all_elems = []
        for i in m:
            new_words = []
            clean_i = regPunct.sub("", i)
            clean_i = regOther.sub("", clean_i)
            clean_i = regTire.sub(" ", clean_i)
            new_words.append(clean_i.split())
            all_elems.append(new_words)

        g = open('stopwords.txt', 'r')
        g = g.read()
        g = g.split()

        for elem in all_elems:
            for i in elem:
                for word in i:
                    ana = morph.parse(word)
                    first = ana[0]
                    for stop in g:
                        if first.normal_form == stop:
                            try:
                                #print(first.normal_form)
                                index_w = i.index(word)
                                del i[index_w]
                            except ValueError:
                                pass

        for elem in all_elems:
            for i in elem:
                if len(i) == 0:
                    try:
                        all_elems.remove(elem)
                    except ValueError:
                        pass

        N = nx.Graph()

        for elem in all_elems:
            for i in elem:
                dict = {}
                for word in i:
                    dict[i.index(word)] = word
                    for elem1 in all_elems:
                        for i1 in elem1:
                            dict1 = {}
                            for word1 in i1:
                                dict1[i1.index(word1)] = word1
                                #if len(N.nodes()) <= 50:
                                if word == word1:
                                    N.add_node(word)
                                    N.add_node(dict.get(i.index(word) + 1))
                                    N.add_node(dict.get(i.index(word) - 1))
                                    N.add_node(dict1.get(i1.index(word1) + 1))
                                    N.add_node(dict1.get(i1.index(word1) - 1))
                                    N.add_edge(word,
                                               dict1.get(i.index(word) + 1))
                                    N.add_edge(word,
                                               dict1.get(i.index(word) - 1))
                                    N.add_edge(word,
                                               dict1.get(i1.index(word1) + 1))
                                    N.add_edge(word,
                                               dict1.get(i1.index(word1) - 1))
        N.remove_node(None)
        pos = nx.spring_layout(N)
        nx.draw_networkx_nodes(N, pos, node_color='red', node_size=10)
        nx.draw_networkx_edges(N, pos, edge_color='blue')
        nx.draw_networkx_labels(N, pos, font_size=8, font_family='Arial')
        plt.axis('off')
        plt.savefig('static/graph.png', dpi=300, format='png')
        nodes = N.number_of_nodes()
        edges = N.number_of_edges()
        return render_template('thanks.html', nodes=nodes, edges=edges)
        #plt.show()
    return redirect(url_for(''))
Exemplo n.º 52
0
import networkx as nx
import matplotlib.pyplot as plot

A = nx.Graph()
A.add_edges_from([('R1', 'Sw1'), ('Sw1', 'Sw2'), ('Sw1', 'Sw3'),
                  ('Sw2', 'Pc2'), ('Sw2', 'Pc3'), ('Sw3', 'Pc4'),
                  ('Sw3', 'Pc5')])

posicion = nx.spring_layout(A)
nx.draw_networkx_nodes(A, posicion, node_size=800)
nx.draw_networkx_edges(A, posicion, width=2)
nx.draw_networkx_labels(A, posicion, font_size=11, font_family='arial')

plot.axis('off')
plot.savefig("Graf1.eps")
plot.show(A)
Exemplo n.º 53
0
def draw_graph(graph,
               labels=None,
               node_color='blue',
               node_size=1600,
               graph_layout='shell',
               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'):

    # create networkx graph
    G = nx.Graph()

    # add edges
    for edge in graph:
        G.add_edge(edge[0], edge[1])

    # these are different layouts for the network you may try
    # shell seems to work best
    if graph_layout == 'spring':
        graph_pos = nx.spring_layout(G)
    elif graph_layout == 'spectral':
        graph_pos = nx.spectral_layout(G)
    elif graph_layout == 'random':
        graph_pos = nx.random_layout(G)
    else:
        graph_pos = nx.shell_layout(G)

    nx.draw_networkx_nodes(G,
                           graph_pos,
                           node_size=node_size,
                           alpha=node_alpha,
                           node_color=node_color)

    nx.draw_networkx_edges(G,
                           graph_pos,
                           width=edge_tickness,
                           alpha=edge_alpha,
                           edge_color=edge_color)
    nx.draw_networkx_labels(G,
                            graph_pos,
                            font_size=node_text_size,
                            font_family=text_font)

    if labels is None:
        labels = range(len(graph))

    edge_labels = dict(zip(graph, labels))
    nx.draw_networkx_edge_labels(G,
                                 graph_pos,
                                 edge_labels=edge_labels,
                                 label_pos=edge_text_pos)
    grafito = {}
    # show graph
    for conta in xrange(len(graph)):
        grafito[graph[conta][0]] = G.degree(graph[conta][0])
    grafito = list(grafito.items())
    return grafito
Exemplo n.º 54
0
def drawNetwork(Gx=None,
                Gxu=None,
                nodes=None,
                edges=None,
                forceiter=100,
                grphtype='undirected',
                dx=10,
                dy=10,
                colormap='jet',
                scale=1.0,
                layout='force',
                drawlabels=True,
                giant=False,
                equi=False,
                res=0.5,
                k=None,
                edge_labels=False,
                font=12):

    if grphtype == 'directed':
        if Gx == None and Gxu == None:
            Gx = nx.from_pandas_edgelist(edges,
                                         'Source',
                                         'Target', ['Weight'],
                                         create_using=nx.DiGraph())
            Gxu = nx.from_pandas_edgelist(edges, 'Source', 'Target',
                                          ['Weight'])
        if giant:
            print('not implemented')
    else:
        if Gx == None:
            Gx = nx.from_pandas_edgelist(edges, 'Source', 'Target', ['Weight'])
        if giant and not nx.is_connected(Gx):
            S = [Gx.subgraph(c).copy() for c in nx.connected_components(Gx)]
            size = []
            for s in S:
                size.append(len(s))
            idsz = np.argsort(size)
            print('found ', np.array(size)[idsz], ' connected components')
            index = int(input('enter index '))
            Gx = S[idsz[index]]
    if layout == 'force' or layout == None:
        pos = nx.spring_layout(Gx, k=1, iterations=forceiter)
    elif layout == 'spiral':
        pos = nx.spiral_layout(Gx, equidistant=equi, resolution=res)
    df = np.array(nodes)
    if len(df.shape) == 1:
        df = np.reshape(df, (len(df), 1))
    nodelabel = dict(
        zip(np.linspace(0, len(df[:, 0]) - 1, len(df[:, 0]), dtype=int),
            df[:, 0]))
    labels = {}
    for idx, node in enumerate(Gx.nodes()):
        labels[node] = nodelabel[int(node)]
    if grphtype == 'directed':
        part = cm.best_partition(Gxu)
        values = [part.get(node) for node in Gxu.nodes()]
    else:
        part = cm.best_partition(Gx)
        values = [part.get(node) for node in Gx.nodes()]
    d = nx.degree(Gx)
    dsize = [(d[v] + 1) * 100 * scale for v in Gx.nodes()]
    plt.figure(figsize=(dx, dy))
    if edge_labels:
        edge_labels = nx.get_edge_attributes(Gx, 'Label')
        nx.draw_networkx_edge_labels(Gx, pos, edge_labels, font_size=font)
    nx.draw_networkx(Gx,
                     pos=pos,
                     labels=labels,
                     with_labels=drawlabels,
                     cmap=plt.get_cmap(colormap),
                     node_color=values,
                     node_size=dsize)
    plt.show()
# figure out total collaborations
collabMat_sen = np.zeros((len(connMat_sen), len(connMat_sen)))
billThresh = 15
for i in range(0, len(connMat_sen)):
    for j in range(0, len(connMat_sen)):
        totalAppearances = connMat_sen[i, j] + connMat_sen[j, i]
        if totalAppearances > billThresh:
            collabMat_sen[i, j] = 1
            collabMat_sen[j, i] = collabMat_sen[i, j]

###########################################################
# create network from connectivity matrix for House of Reps
G = nx.from_numpy_matrix(collabMat_rep)

# get node positions
pos = nx.spring_layout(G, dim=3)

# get x and y coordinates of nodes
Xn = [pos[k][0]
      for k in range(0, G.number_of_nodes())]  # x-coordinates of nodes
Yn = [pos[k][1] for k in range(0, G.number_of_nodes())]  # y-coordinates
Zn = [pos[k][2] for k in range(0, G.number_of_nodes())]  # y-coordinates

# populate node edges
Edges = G.edges()
Xe = []
Ye = []
Ze = []
for e in Edges:
    Xe += [pos[e[0]][0], pos[e[1]][0], None]  # x-coordinates of edge ends
    Ye += [pos[e[0]][1], pos[e[1]][1], None]
Exemplo n.º 56
0
import numpy as np
import csv
import networkx as nx  # 导入建网络模型包,命名ne
import matplotlib.pyplot as mp  # 导入科学绘图包,命名mp

# BA scale-free degree network graphy
L = 100
BA = nx.barabasi_albert_graph(L, 1)  #1000个节点,初始m0=2
ps = nx.spring_layout(BA)  # 布置框架
nx.draw(BA, ps, with_labels=None, node_size=20)
mp.show()

G = []
for i in range(0, L):  # 记录所有节点的邻居节点
    G.append(list(BA.neighbors(i)))

links = []
#link = np.zeros(L)
for i in range(0, L):
    link = np.zeros(L)
    linklist = link.tolist()
    for j in range(0, L):
        if j in G[i]:
            linklist[j] = 1
    links.append(linklist)
print(links)

np.savetxt('links.csv', links, delimiter=',')

for i in range(0, L):  #将各个节点的额lable(ID)插入到表格的第一列
    degree = len(G[i])
Exemplo n.º 57
0
    net=net,
    colors='pairwise_sharp',
    sizes='neighborhood_watch_sharp')

sharp_sizes = []
for s in sizes:
    if s <= 5:
        sharp_sizes.append(1)
    elif s <= 13:
        sharp_sizes.append(2)
    else:
        sharp_sizes.append(3)

sizes = [s * 2000 for s in sharp_sizes]

pos_spring = nx.spring_layout(net)
pos_circular = nx.circular_layout(net)
print(net)
network_visualization.draw_network(net,
                                   node_labels,
                                   color_map=color_map,
                                   draw_edges=False,
                                   draw_labels=False,
                                   name=folder_path + '/network_pictures/' +
                                   pdb_id + '_color',
                                   figsize=(50, 50),
                                   pos=pos_spring)
network_visualization.draw_network(net,
                                   node_labels,
                                   sizes=sizes,
                                   draw_labels=False,
Exemplo n.º 58
0
def drawGraph(G):
    plt.figure()
    pos = nx.spring_layout(G)
    nx.draw_networkx(G, pos)
    plt.savefig("graph.pdf")
    plt.show()
def draw_graph_centrality2(G,
                           Subsets=[],
                           h=15,
                           v=10,
                           deltax=0,
                           deltay=0,
                           fontsize=18,
                           k=0.2,
                           arrows=False,
                           node_alpha=0.3,
                           l_alpha=1,
                           node_color='blue',
                           centrality=nx.degree_centrality,
                           font_color='black',
                           threshold=0.01,
                           multi=3000,
                           edge_color='olive',
                           colstart=0.2,
                           coldark=0.5):

    from pylab import rcParams
    import matplotlib.pyplot as plt
    from matplotlib import colors as mcolors

    colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
    node_dict = centrality(G)
    subnodes = dict(
        {x: node_dict[x]
         for x in node_dict if node_dict[x] >= threshold})
    #print(subnodes)
    x, y = rcParams['figure.figsize']
    rcParams['figure.figsize'] = h, v

    ax = plt.subplot()
    ax.set_xticks([])
    ax.set_yticks([])
    #G = G.subgraph(subnodes)
    glob_col = sns.hls_palette(len(G), h=colstart, l=coldark)[0]
    pos = nx.spring_layout(G, k=k)
    labelpos = dict({k: (pos[k][0] + deltax, pos[k][1] + deltay) for k in pos})
    #print(labelpos)
    #print(pos)
    if l_alpha <= 1:
        nx.draw_networkx_labels(G,
                                labelpos,
                                font_size=fontsize,
                                alpha=l_alpha,
                                font_color=font_color)
    sub_color = 0
    if Subsets != []:
        i = 0
        colpalette = sns.hls_palette(len(Subsets), h=colstart, l=coldark)
        #print(colpalette)
        for Sub in Subsets:
            sublist = dict({x: subnodes[x] for x in subnodes if x in Sub})
            #print(sublist)
            #sub_col = list(colors.values())[np.random.randint(20,100)]
            sub_col = colpalette[i]
            #print(i, sub_col, sublist.keys())
            #print(i, sub_col)
            nx.draw_networkx_nodes(
                G,
                pos,
                alpha=node_alpha,
                node_color=[sub_col],
                nodelist=[x for x in sublist.keys()],
                node_size=[v * multi for v in sublist.values()])
            i += 1
    else:
        nx.draw_networkx_nodes(
            G,
            pos,
            alpha=node_alpha,
            node_color=glob_col,
            nodelist=subnodes.keys(),
            node_size=[v * multi for v in subnodes.values()])
        True

    nx.draw_networkx_edges(G,
                           pos,
                           alpha=0.1,
                           arrows=arrows,
                           edge_color=edge_color)

    rcParams['figure.figsize'] = x, y
    return
Exemplo n.º 60
0
 def test_spring_fixed_without_pos(self):
     G = nx.path_graph(4)
     pytest.raises(ValueError, nx.spring_layout, G, fixed=[0])
     pos = {0: (1, 1), 2: (0, 0)}
     pytest.raises(ValueError, nx.spring_layout, G, fixed=[0, 1], pos=pos)
     nx.spring_layout(G, fixed=[0, 2], pos=pos)  # No ValueError