Exemplo n.º 1
0
 def plotGraph(self, path):
     if self.graph is None:
         raise Exception("The graph has not been generated")
     values = [self.colorScheme(n) for n in self.graph.nodes()]
     nx.draw_spring(self.graph, cmap="jet", node_color=values, node_size=100)
     plt.savefig(path)
     plt.close()
Exemplo n.º 2
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.º 3
0
def construct_de_bruijn_velvet(kmers, draw, outfile):
	#make list of k-1mers for quick edge construction
	k1mers = [x[:-1] for x in kmers.keys()]
	k1mers_array = np.array(k1mers)

	#find overlaps
	edge_list = []
	for kmer in kmers.keys():
		matches = np.where(k1mers_array==kmer[1:])
		for match in matches[0]:
			#print match
			edge_list.append((kmer, kmers.keys()[match]))

	#make graph
	G = nx.DiGraph()
	#add seq_kmers as nodes and overlaps as edges
	for kmer in kmers.items():
		G.add_node(kmer[0], num=kmer[1])
	G.add_edges_from(edge_list)

	# draw the graph if desired
	if draw == "True":
		nx.draw_spring(G)
		plt.show()

	#output adjacency list format of the graph if desired
	if outfile != "":
		nx.write_adjlist(G, outfile)

	return G
def get_communities(graph):
	betweenness = nx.edge_betweenness_centrality(graph)
	sorted_betweeness = [x[0] for x in sorted(betweenness.items(), key = lambda x : x[1], reverse = True)]
	best_partitions = []
	max_modularity = -1.0
	graph_copy = graph.copy()
	while sorted_betweeness:
		communities = [list(x) for x in nx.connected_components(graph_copy)]
		partitions = {}
		for i in range(len(communities)):
			for node in communities[i]:
				partitions[node] = i
		modularity = community.modularity(partitions, graph_copy)
		if modularity > max_modularity:
			best_partitions = communities
			max_modularity = modularity
		elif modularity <= max_modularity:
			break;
		graph_copy.remove_edge(*sorted_betweeness[0])
		del sorted_betweeness[0]
	for partition in best_partitions:
		print sorted(partition)
	val_map = {}
	for partition in best_partitions:
		value = random.random()
		while value in val_map.values():
			value = random.random()
		for node in partition:
			val_map[node] = value
	values = [val_map.get(node) for node in graph.nodes()]
	nx.draw_spring(graph, node_color = values, node_size = 500, with_labels = True)
	plt.savefig(sys.argv[2])
Exemplo n.º 5
0
def get_topics_noun_phrases(num_news, draw=False, url='http://cnn.com'):

    texts = get_news(url, num_news)

    gb = NounPhraseGraphBuilder(text_processing.clean_punctuation_and_stopwords)
    gb.load_texts(texts)
    G = gb.create_graph()
    print "Graph built"

    partition = community.best_partition(G)
    words_by_part = get_words_by_partition(partition)

    print_topics_from_partitions(G, words_by_part, 10)

    mod = community.modularity(partition,G)
    print("modularity:", mod)

    #print_topics_from_partitions(G, words_by_part, 10)
    if draw:
        values = [partition.get(node) for node in G.nodes()]
        nx.draw_spring(G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
        plt.show()

    topics = get_topics_from_partitions(G, words_by_part, 10)

    return G, topics
def print_graph_nx(vertices, edges, name, draw_spring=False, print_dist=False):
  G=nx.DiGraph()
  labels = []

  for v in vertices:
    G.add_node(v)

  for v in vertices:
    for e in edges:
      if(len(e)) > 2:
        G.add_edge(e[0], e[1], weight=int(e[2]))
      else:
        G.add_edge(e[0], e[1])

  print("Nodes of graph: ")
  print(G.nodes())
  print("Edges of graph: ")
  print(G.edges())

  if not draw_spring:
    nx.draw(G, with_labels=True, node_color='y')
  else:
    nx.draw_spring(G, with_labels=True, node_color='y')
  #nx.draw_networkx_edge_labels(G,labels)
  plt.savefig("%s.png" % name) # save as png
  #plt.show()
  plt.clf()
Exemplo n.º 7
0
def draw_graph(graph, showLabels = True):

    # extract nodes from graph
    nodes = set([n1 for n1, n2 in graph] + [n2 for n1, n2 in graph])

    # create network graph
    G=nx.Graph()

    # add nodes
    for node in nodes:
        G.add_node(node)

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

    # draw graph 1 in shell layout
    pos = nx.shell_layout(G)
    nx.draw(G, pos)
    plt.figure()

    # draw graph 2 with a random layout
    # might need to zoom in to see edges
    # labels are now on top of the nodes
    nx.draw_random(G)
    plt.figure()
    nx.draw_spring(G, node_size=100, with_labels=showLabels, font_size=16, edge_color="grey", width=0.5)

    # draw graph 3 the standard way and save
    plt.savefig("fig1.png")
    plt.show()
Exemplo n.º 8
0
def lattice_plot(component_list, file_path):
    """
    Creates a lattice style plot of all graph components
    """
    graph_fig=plt.figure(figsize=(20,10))    # Create figure
    
    # Set the number of rows in the plot based on an odd or
    # even number of components  
    num_components=len(component_list)
    if num_components % 2 > 0:
        num_cols=(num_components/2)+1
    else:
        num_cols=num_components/2
    
    # Plot subgraphs, with centrality annotation
    plot_count=1
    for G in component_list:
        # Find actor in each component with highest degree
        in_cent=nx.degree(G)
        in_cent=[(b,a) for (a,b) in in_cent.items()]
        in_cent.sort()
        in_cent.reverse()
        high_in=in_cent[0][1]
        
        # Plot with annotation
        plt.subplot(2,num_cols,plot_count)
        nx.draw_spring(G, node_size=35, with_labels=False)
        plt.text( 0,-.1,"Highest degree: "+high_in, color="darkgreen")
        plot_count+=1
    
    plt.savefig(file_path)
Exemplo n.º 9
0
    def draw_graph(self, G, node_list=None, edge_colour='k', node_size=15, node_colour='r', graph_type='spring',
                   back_bone=None, side_chains=None, terminators=None):
        # determine nodelist
        if node_list is None:
            node_list = G.nodes()
        # determine labels
        labels = {}
        for l_atom in G.nodes_iter():
            labels[l_atom] = l_atom.symbol

        # draw graphs based on graph_type
        if graph_type == 'circular':
            nx.draw_circular(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'random':
            nx.draw_random(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spectral':
            nx.draw_spectral(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spring':
            nx.draw_spring(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'shell':
            nx.draw_shell(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                          edge_color=edge_colour, node_color=node_colour)
        # elif graph_type == 'protein':
        # self.draw_protein(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
        #                   edge_color=edge_colour, node_color=node_colour, back_bone, side_chains, terminators)
        else:
            nx.draw_networkx(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        plt.show()
Exemplo n.º 10
0
	def randBearGenealogy(self):
		"""show all direct older relatives of a random bear"""
		G = nx.Graph()
		bear = self.getRandomBear()
		self.helpGenes(G, bear.mom)
		self.helpGenes(G, bear.dad)
		nx.draw_spring(G)
		plt.show()
Exemplo n.º 11
0
def draw_Graph( G ):
	nx.draw_spring(G,
			node_color=[float(G.degree(v)) for v in G],
			node_size=40,
			with_labels=False,
			cmap=plt.cm.Reds,
			)
	plt.show()
Exemplo n.º 12
0
def main():
    if len(sys.argv) > 1:
        id = sys.argv[1]
    else:
        id = input("Enter user ID or screen_name: ").lstrip()

    # Authorization
    session = vk.AuthSession(access_token=VkData.TOKEN)
    vk_api = vk.API(session, v=VkData.VERSION)

    # If user enters screen_name, we need to get his ID
    id = vk_api.users.get(user_ids=id)[0]["id"]

    # Friends Graph is dictionary
    # Key - friend, graph vertex
    # Value - list of mutual friends, adjacent vertices
    graph = {}

    # Get list of friends for entered ID
    friends = get_friends(vk_api, id)

    # Fill graph
    for friend in friends:
        print('Processing', "\tid: ", friend.id, "\tName : ",
              friend.first_name, friend.last_name)

        # If the profile is not hidden
        if not friend.is_closed:
            # Get friends of friend
            all_friends = get_friends(vk_api, friend.id)

            # Find mutual friends
            mutual = []

            for i in all_friends:
                for j in friends:
                    if i.id == j.id:
                        mutual.append(j)

            # Add value in dictionary
            graph[friend] = mutual
        else:
            graph[friend] = list()

    # Graph visualisation
    g = nx.from_dict_of_lists(graph)

    options = {
        'node_color': 'red',
        'node_size': 100,
        'line_color': 'black',
        'with_labels': True,
        'font_color': 'black',
        'style': 'dotted',
    }

    nx.draw_spring(g, **options)
    plt.show()
Exemplo n.º 13
0
def graph_object(data_1, data_2, data_3):

    #instantiate a networkx graph object
    G = nx.Graph()
    head = 1171944902
    G.add_node(head)

    #converts dictionaries into list format from data points 1,2 and 3

    list_data_1 = list(data_1.keys())
    G.add_nodes_from(list_data_1)
    list_data_2 = []

    for element in data_2:
        for i in element.keys():
            list_data_2.append(i)

    list_data_3 = []

    for element in data_3:
        for i in element.keys():
            list_data_3.append(i)

    #add edges from my account and my top 5 most popular friends
    for i in range(0, len(list_data_1)):
        G.add_edges_from([(1171944902, list_data_1[i])])

    #add edges between distance 1 friends and distance 2 friends
    for j in range(0, len(data_2)):
        for k in list(data_2[j].keys()):
            G.add_edges_from([(list_data_1[j], k)])

    #add edges between distance 2 friends and distance 3 friends
    for l in range(0, len(data_3)):
        for m in list(data_3[l].keys()):
            G.add_edges_from([(list_data_2[l], m)])

    #Just generate a little title for my graph plot
    plt.title("Daniel Fatade's Social Media Network")
    nx.draw_spring(G, node_color='bisque', with_labels=True)

    #This saves the graph figure.
    #plt.savefig('my_network_graph')

    #These functions calculate the diamter of the graph, the number of nodes and edges present in the graph
    #and the average distance of the graph

    n_edges = G.number_of_edges()
    diameter = nx.diameter(G)
    average_dist = nx.average_shortest_path_length(G)

    n_nodes = G.nodes()

    print("This graph contains {0} distinct nodes with {1} edges. ".format(
        len(n_nodes), n_edges))
    print("The Diameter of this network is: {0} ".format(diameter))
    print("The average distance between each node in the Graph is: {0}".format(
        average_dist))
Exemplo n.º 14
0
def main():
    Arestas = np.loadtxt('ha30_dist.txt')
    G = nx.from_numpy_matrix(Arestas)
    A = kruskal(G)

    print(A.edges)

    nx.draw_spring(A, with_labels=True)
    plt.savefig("grafo_mst.png")
Exemplo n.º 15
0
def main():
    """For testing with iPython"""
    # nx.draw_spring(g, with_labels=True)
    dfs = nx.Graph()
    # for k, v in tarjan(draw_network(), "sum1")[0].items():
    # for k, v in tarjan(draw_small(), "A")[0].items():
    for k, v in tarjan(draw_wiki(), "A")[0].items():
        dfs.add_edge(k, v)
    nx.draw_spring(dfs, with_labels=True)
Exemplo n.º 16
0
def draw_graph_spring(y, clusters='blue', ns=30):
    G = nxG(y)

    plt.figure()
    nx.draw_spring(G,
                   cmap=plt.get_cmap('jet'),
                   node_color=clusters,
                   node_size=30,
                   with_labels=False)
def draw_graph_labels(labels):
    d = array_to_dict(labels)
    values = [d.get(node) for node in G.nodes()]
    nx.draw_spring(G,
                   map=plt.get_cmap('jet'),
                   node_color=values,
                   node_size=30,
                   with_labels=False)
    plt.show()
Exemplo n.º 18
0
def showGraph( graph ) :
	# pos = nx.spring_layout(graph, k=1)
	# nx.draw_networkx_nodes(graph, pos, node_size=4000, node_color="white")
	# nx.draw_networkx_edges(graph, pos, width=3, alpha=0.5, edge_color="black", arrows=True)
	# nx.draw_networkx_labels(graph, pos, font_size=12)
	# nx.draw_networkx_edge_labels(graph, pos, label_pos=0.6, font_size = 10)
	# plt.axis('off')
	nx.draw_spring (graph)
	plt.show ()
Exemplo n.º 19
0
def show(graph):
    # nx.draw(graph, with_labels=True, font_weight='bold')
    # nx.draw_circular(graph, with_labels=True, font_weight='bold')
    # nx.draw_kamada_kawai(graph, with_labels=True, font_weight='bold')
    # nx.draw_spectral(graph, with_labels=True, font_weight='bold')
    nx.draw_spring(graph, with_labels=True, font_weight='bold')
    # nx.draw(graph, with_labels=True, font_weight='bold')
    # nx.draw(graph, with_labels=True, font_weight='bold')
    plt.show()
Exemplo n.º 20
0
 def graph(self, plot=False):
     import networkx as nx
     G = nx.DiGraph()
     for n1,n2 in self.probas:
         G.add_edge(n1,n2,{'p':self.probas[n1,n2]})
     if plot:
         nx.draw_spring(G)
     else:
         return G
Exemplo n.º 21
0
def main():
	cities = {}
	paths = defaultdict(int)
	ants = []

	#init city data
	with open('cities.txt') as cityFile:
		for line in cityFile:
			line = line.split() # to deal with blank 
			if line:
				cities[ line[0] ] = int(line[1])

	numberOfAnts = int(len(cities)*1.5)

	numberOfIterations = 10
	optimalDistance = 1000000
	optimalPath = []
	money = 0
	

	for i in range(numberOfIterations):
			#init distance data
		with open('distances.txt') as distanceFile:
			for line in distanceFile:
				line = line.split()
				if line:
					initMatrixAtIndexes(paths,line[0],line[1],int(line[2]),cities)

		ALPHA = random.randint(1,1)
		BETA = random.randint(1,1)
		#EVAPORATION_RATE = random.random()
		ants = []
		for i in range(numberOfAnts):
			a = Ant('INITIAL')
			ants.append(a)

		for a in ants:
			#Tour until stuck or until visited all cities
			for i in range(len(cities)):
				if not a.hasVisitedAllCities(cities) and not a.isStuck():
					evaporatePheromones(paths,ants)
					a.moveToNextEdge(paths)
				elif not a.hasReturnedHome() and not a.isStuck():
					evaporatePheromones(paths,ants)
					a.returnToStartingCity(paths)
			if (a.getTravelledDistance()<optimalDistance and not a.isStuck()):
				optimalPath = a.getPath()
				optimalDistance = a.getTravelledDistance()
				money = a.getMoney()		
	g=nx.DiGraph()
		
	for i in range (len(optimalPath)-1):
		g.add_weighted_edges_from([(optimalPath[i],optimalPath[i+1],paths[(optimalPath[i],optimalPath[i+1])]['distance'])])
	nx.draw_spring(g)
	plt.savefig("file.png")
	nx.write_dot(g,'file.dot')
	print optimalDistance, optimalPath, money
Exemplo n.º 22
0
def ego():
    '''
    This node is deceptively connected because it's from the index
    (page 750 of volume2.pdf).
    '''
    g_9_56_090 = nx.ego_graph(g, '9.56.090')
    nx.draw_spring(g_9_56_090)
    plt.savefig("9.56.090.png")
    print nodes['9.56.090']
Exemplo n.º 23
0
def communities(publications: List[Tuple[int, Set[int]]]) -> None:
    graph = get_collaboration_graph(publications, 2006, 2016)

    partition = community_louvain.best_partition(graph)
    values = [partition.get(node) for node in graph.nodes()]
    
    networkx.draw_spring(graph, cmap=matplotlib.pyplot.get_cmap('tab20'), node_size=60, node_color=values, font_size=8, with_labels=True)

    matplotlib.pyplot.show()
Exemplo n.º 24
0
def test_edge_colormap():
    colors = range(barbell.number_of_edges())
    nx.draw_spring(
        barbell,
        edge_color=colors,
        width=4,
        edge_cmap=plt.cm.Blues,
        with_labels=True,
    )
def main(args):
    if len(args) != 1:
        sys.exit("Usage: python ?.py <graphml file>")

    net = args[0]
    G = networkx.read_graphml(net)
    G = networkx.convert_node_labels_to_integers(G)
    investment_dataframe = pandas.read_csv('investment.csv', header=None)
    investment_narray = numpy.array(investment_dataframe)  #np.ndarray()
    investment_list = investment_narray.tolist()  #list
    investment = []
    nodes_color = []
    nodes_size = []
    for i in range(len(investment_list)):
        [inv] = investment_list[i]
        investment.append(inv)
    '''度的节点size大'''
    for i in range(len(G)):
        d = G.degree()[i]
        if d >= 0 and d < 2:
            nodes_size.append(20)
        elif d >= 2 and d < 4:
            nodes_size.append(50)
        elif d >= 4 and d < 6:
            nodes_size.append(100)
        elif d >= 6 and d < 8:
            nodes_size.append(160)
        elif d >= 8 and d < 10:
            nodes_size.append(200)
        elif d >= 10:
            nodes_size.append(1000)
    '''投资大的颜色偏红'''

    for i in range(len(G)):
        invest = investment[i]
        if invest >= 0 and invest < 0.2:
            nodes_color.append('#FFFFB9')
        elif invest >= 0.2 and invest < 0.4:
            nodes_color.append('#FFFF37')
        elif invest >= 0.4 and invest < 0.6:
            nodes_color.append('#FF8000')
        elif invest >= 0.6 and invest < 0.8:
            nodes_color.append('#F75000')
        elif invest >= 0.8 and invest < 0.9:
            nodes_color.append('#F75000')
        elif invest >= 1:
            nodes_color.append('#EA0000')

    networkx.draw_spring(G,
                         width=0.5,
                         with_labels=False,
                         font_size=10,
                         node_size=nodes_size,
                         node_color=nodes_color,
                         node_width=0)
    plt.show()  #可以将这个网络图形显示出来
    plt.savefig('RELITU.png')
Exemplo n.º 26
0
 def draw_community(self):
     part = community.best_partition(self.graph)
     values = [part.get(node) for node in self.graph.nodes()]
     nx.draw_spring(self.graph,
                    cmap=plt.get_cmap('jet'),
                    node_color=values,
                    node_size=30,
                    with_labels=False)
     plt.show()
Exemplo n.º 27
0
	def showGraph(self):
		"""show a graph of all bears that are alive"""
		G = nx.Graph()
		for bear in self.bears:
			mom = bear.mom
			dad = bear.dad
			if dad!=None and mom != None:
				G.add_edges_from([(str(mom),str(mom)+"-"+str(dad)),(str(mom)+str(dad),str(dad)), (str(mom)+str(dad), str(bear))])
		nx.draw_spring(G)
		plt.show()
Exemplo n.º 28
0
def graphattempt():
	G = nx.Graph() 
	for friend in frndct:
		for person in frndct[friend]:
			G.add_edge(friend, person)
	
	nx.write_gexf(G, 'networkforge.gexf')
	pos=nx.spring_layout(G)
	nx.draw_spring(G, with_labels=True, font_size=20, font_color='black', node_color = "steelblue") 
	plt.show()
def plot_graph_community(graph):
    parts = community_louvain.best_partition(graph)
    values = [parts.get(node) for node in graph.nodes()]
    nx.draw_spring(graph,
                   cmap=plt.get_cmap('jet'),
                   node_color=values,
                   node_size=35,
                   with_labels=False)
    plt.axis('off')
    plt.show()
Exemplo n.º 30
0
def plot_graph(graph, race_dict):
    print(graph.number_of_nodes())
    # print(graph.nodes[:5])
    print(graph.number_of_edges())
    # nx.draw(graph)
    nx.draw_spring(graph)

    # plt.savefig("graph.png")  # save as png
    plt.show()
    pass
Exemplo n.º 31
0
def test_remove_vertices(g):
    g_save = g.copy(False)
    g_save.remove_node(1)
    g_save.remove_node(2)
    g_save.remove_node(3)
    g_save.remove_node(4)
    g_save.remove_node(5)
    nx.draw_spring(g_save, with_labels=True)
    plt.savefig("Illustrations/my_graph_with_less_vertices.pdf")
    plt.close()
Exemplo n.º 32
0
def main():
    n = 16
    m = 25
    G = nx.gnm_random_graph(n, m)
    # nx.draw(G, with_labels=True, font_weight='bold')
    nx.draw_spring(G, with_labels=True, font_weight='bold')
    plt.show()

    for node in nx.nodes(G):
        pass
Exemplo n.º 33
0
def bn_ex():
    print("BN Example")
    fig, ax = newfig(1.0)

    G = nx.DiGraph()
    for (p, q) in [('A', 'C'), ('B', 'C'), ('C', 'D')]:
        G.add_edge(p, q)

    nx.draw_spring(G, node_color='w', ax=ax, with_labels=True, font_size=10)
    savefig('bn_ex')
Exemplo n.º 34
0
def p_create(p):
  """
  create : parameter
         | equal_var
         | empty 
  """
  print("TREE", p[1])
  print('Status: ' + str(use(p[1])))
  nx.draw_spring(graph(p[1]), with_labels=True)
  plt.savefig('output.png')
Exemplo n.º 35
0
def save_graph(graph):
    """
    Networkx draw function does not look nice.
    Function needs improvements in the future.
    """
    nx.draw_spring(graph, with_labels = True)
    plt.draw()
    #plt.show()
    plt.savefig('graph_with_labels.png')
    plt.clf()
    def get_motif_example(self, motif_length=25):
        """Method that gets an example motif of motif_length."""
        motifs = mf.get_motifs(self.project_ids, motif_length, self.num_motifs_to_sample, self.commits_dl)
        second_most_common_motif = sorted(motifs, key=motifs.get, reverse=True)[1]

        fig, ax = plt.subplots()
        nx.draw_spring(second_most_common_motif, node_size=100, ax=ax)
        fig.suptitle('Common Git Motif \n Length {}'.format(motif_length), fontsize=20)

        fig.savefig('results/motif_example.png')
        return fig
Exemplo n.º 37
0
def buffer_match_mappings(graph, title='buffer matches'):
    labels = nx.get_node_attributes(graph, 'label')
    matches_colour = {
        i: ("#00f208" if
            (graph.nodes[i]['buffer_match'] == True) else "#c0c1c2")
        for i in graph.nodes
    }
    nx.draw_spring(graph,
                   node_color=list(matches_colour.values()),
                   labels=labels)
    plt.show()
Exemplo n.º 38
0
def show_graph( Graph ):
	edges=[]
	for k,v in g.items():
		for x in v:
			edges.append((k,x))
	
	G=nx.Graph()
	G.add_edges_from(edges)

	nx.draw_spring(G)
	plt.show()
Exemplo n.º 39
0
def transitive_closure_road_accident():
    print(
        "Znajdź domknięcie przechodnie relacji hiperonimi dla pierwszego znaczenia wyrażenia wypadek drogowy i przedstaw je w postaci grafu skierowanego."
    )
    meaning = d.WNQUERY.lookUpSense('wypadek drogowy', 1, 'n')
    dfs(d.WNQUERY, meaning.wnid, 'n', 'hypernym')
    diGraph = networkx.DiGraph()
    diGraph.add_edges_from(graph)
    plt.figure(figsize=(12, 3))
    networkx.draw_spring(diGraph, with_labels=True)
    plt.show()
Exemplo n.º 40
0
 def test_draw(self):
     #         hold(False)
     N = self.G
     nx.draw_spring(N)
     pylab.savefig("test.png")
     nx.draw_random(N)
     pylab.savefig("test.ps")
     nx.draw_circular(N)
     pylab.savefig("test.png")
     nx.draw_spectral(N)
     pylab.savefig("test.png")
Exemplo n.º 41
0
    def test_draw(self):
#         hold(False)
        N=self.G
        nx.draw_spring(N)
        pylab.savefig("test.png")
        nx.draw_random(N)
        pylab.savefig("test.ps")
        nx.draw_circular(N)
        pylab.savefig("test.png")
        nx.draw_spectral(N)
        pylab.savefig("test.png")
Exemplo n.º 42
0
    def draw_and_show_with_edge_labels(self):
        """
        Draws the graph and displays it with node/edge labels displays. This is somewhat experimental and can be buggy
        dependent on the number of nodes and how edge labels are displayed.

        :return:
        """
        nx.draw_spring(self.current_graph, with_labels=True)
        nx.draw_networkx_edge_labels(self.current_graph, pos=nx.spring_layout(self.current_graph))
        plt.waitforbuttonpress()
        return True
def run_mini_pipeline():
    atlas = datasets.fetch_atlas_msdl()
    atlas_img = atlas['maps']
    labels = pd.read_csv(atlas['labels'])['name']

    masker = NiftiMapsMasker(maps_img=atlas_img, standardize=True,
                               memory='/tmp/nilearn', verbose=0)

    data = datasets.fetch_adhd(number_subjects)

    figures_folder = '../figures/'
    count=0
    for func_file, confound_file in zip(data.func, data.confounds):
        
        # fit the data to the atlas mask, regress out confounds
        time_series = masker.fit_transform(func_file, confounds=confound_file)

        correlation = np.corrcoef(time_series.T)

        #plotting starts here
        plt.figure(figsize=(10, 10))
        plt.imshow(correlation, interpolation="nearest")
        x_ticks = plt.xticks(range(len(labels)), labels, rotation=90)
        y_ticks = plt.yticks(range(len(labels)), labels)
        corr_file = figures_folder+'subject_number_' + str(count) + '_correlation.pdf'
        plt.savefig(corr_file)

        atlas_region_coords = [plotting.find_xyz_cut_coords(img) for img in image.iter_img(atlas_img)]
        threshold = 0.6
        plotting.plot_connectome(correlation, atlas_region_coords, edge_threshold=threshold)
        connectome_file = figures_folder+'subject_number_' + str(count) + '_connectome.pdf'
        plt.savefig(connectome_file)


        #graph setup

        #binarize correlation matrix
        correlation[correlation<threshold] = 0
        correlation[correlation != 0] = 1

        graph = nx.from_numpy_matrix(correlation)

        partition=louvain.best_partition(graph)

        values = [partition.get(node) for node in graph.nodes()]

        plt.figure()
        nx.draw_spring(graph, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=True)
        graph_file = figures_folder+'subject_number_' + str(count) + '_community.pdf'
        plt.savefig(graph_file)

        count += 1

        plt.close('all')
Exemplo n.º 44
0
def draw(draw_graph):
    options = {
        'node_color': 'black',
        'node_size': 50,
        'line_color': 'grey',
        'linewidths': 0,
        'width': 0.1,
        'with_labels': True
    }
    nx.draw_spring(draw_graph, **options)
    plt.show()
def test_multilayer():
    net = Multilayer([2,5,1])
    print net.network_inputs
    print net.network_outputs
    print net.hidden_layers
    print net.network.edges()
    print net.evaluate_pattern([1.0, 1.0])
    import matplotlib.pyplot as plt
    import networkx
    networkx.draw_spring(net.network)
    plt.show()
Exemplo n.º 46
0
    def plot_giant_component(self):
        '''
        Plots the whole graph
        '''
        try:

            nx.draw_spring(self.giant_component)

        except:

            print('Giant component initialized. Run giant_component method')
Exemplo n.º 47
0
def draw_graph(G):
    """
    A helper function to draw a nx graph with community.
    """
    groups =nx.get_node_attributes(G,'club').values()
    color_list = plt.cm.tab10(np.linspace(0, 1, len(groups)))
    color_dict = dict(zip(groups, color_list))
        
    nx.draw_spring(G,seed=0, nodelist=G.nodes(),
                   node_color=[color_dict[x] for x in groups],
                   alpha=0.8)
Exemplo n.º 48
0
def draw_graph(G):
    """
    Genera una imagen con formato .png del grafo.<br/>
    **:param G:** Recibe un grafo no dirigido de tipo networkx.<br/>
    **:return:** Una imagen .png del grafo.<br/>
    """
    nx.draw_spring(G, with_labels=True)
    labels = nx.get_edge_attributes(G, 'costo')
    # nx.draw_networkx_edge_labels(G, nx.spring_layout(G), edge_labels=labels)
    plt.savefig(MEDIA_ROOT + '/item_trazabilidad.png')
    plt.clf()
Exemplo n.º 49
0
def metagraph_to_spring(
        dgl_graph
):  # konwersja grafu dgl_heterograph i wyświetlenie spring_layout
    # link do dokumentacji: https://networkx.org/documentation/stable/reference/generated/networkx.drawing.layout.spring_layout.html
    dgl_metagraph = dgl_graph.metagraph()
    G = nx.MultiGraph()
    G.add_nodes_from(dgl_metagraph.nodes)
    G.add_edges_from(dgl_metagraph.edges)
    pos = nx.spring_layout(G)
    nx.draw_spring(G)
    #return nx.draw(G, pos)
    plt.show()
Exemplo n.º 50
0
def show(W, lamda, f, m):
    fm, fn = np.shape(f)
    print('fm,fn:', fm, fn)

    lamdaIndicies = np.argsort(lamda)
    first = 0
    second = 0
    print(lamdaIndicies[0], lamdaIndicies[1])
    for i in range(fm):
        if lamda[lamdaIndicies[i]].real > 1e-2:  # 找到特征值比较小的2个,但是不为0的!
            print(lamda[lamdaIndicies[i]])
            first = lamdaIndicies[i]
            second = lamdaIndicies[i + 1]
            break
    print(first, second)

    for i in range(m):
        nx_G = read_graph()  # 利用networkx包读取Graph信息

        color = []
        vertex = []
        vertex.append(i)
        for j in range(m):
            if j == i:
                color.append(0.7)
            elif W[i, j] == 0:
                color.append(0.1)  # 为0或1
            else:
                color.append(0.9)
                vertex.append(j)  #顶点j有关的所有边


#        print(vertex)
# 通过相关联的点进行加边
        for ii in range(m):
            for jj in range(m):
                if nx_G.has_edge(ii, jj):
                    if (ii in vertex or jj in vertex):
                        continue
                    else:
                        nx_G.remove_edge(ii, jj)
        """
        fig=plt.figure('lowdata')  
        ax2 = fig.add_subplot(111)
        ax2.scatter(f[:,first], f[:,second],  c=color, cmap=plt.cm.Spectral)
        
        plt.show()
        """

        nx.draw_spring(nx_G, with_labels=True, node_color=color)
        return

    return
Exemplo n.º 51
0
Arquivo: ex7.py Projeto: mat-hek/pjn
def wypadek_drogowy_hypernym(query: WNQuery):
    wnid = query.lookUpSense("wypadek drogowy", 1, "n").wnid
    cl = closure(query, wnid, 'n', 'hypernym')
    cl = [(query.getSynset(a, 'n').toString(), query.getSynset(b,
                                                               'n').toString())
          for (a, b) in cl]

    graph = nx.DiGraph()
    graph.add_edges_from(cl)
    plt.figure(figsize=(15, 10))
    nx.draw_spring(graph, arrows=True, with_labels=True)
    plt.show()
Exemplo n.º 52
0
def graphCommunities(filename):
	"""
	Partitions and colors graphs into communities w/ best_partition.
	Displays graph with spring layout (perhaps spectral would be better?) and saves.
	Unsuccessful attempts made to separate clusters visually.
	"""
	# generate graph
	graph = makeGraphFromJSON(filename)
	name = filename.split(".json")[0]

	# find the groups each node belongs to
	part = community.best_partition(graph)

	# get total number of clusters and set up dictionary
	clusters = {}
	total = max(part.values()) + 1
	for i in range(total):
		clusters[i] = []

	# sort nodes into clusters
	for node, group in part.items():
		clusters[group].append(node)

	# turn clusters into a separate graph
	for c, nodes in clusters.items():
		clusters[c] = graph.subgraph(clusters[c])

	## Now display clustering of original graph by fixing a point from each
	## cluster and letting networkx arrange the rest of nodes

	fixed = {}
	x = 0
	for _, c in clusters.items():
		# find node of highest degree centrality within each cluster
		deg = nx.degree_centrality(c)
		deg = sorted(deg.items(),key=itemgetter(1), reverse=True)[0]
		
		x += 1

	#return clusters, total
	# graph
	fig = plt.figure()
	plt.axis("off")

	#pos = nx.spring_layout(graph, fixed=fixed.keys(), pos=fixed)

	values = [part.get(node) for node in graph.nodes()]

	#nx.draw_networkx(graph, pos=pos, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=True)
	nx.draw_spring(graph, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=True)
	# save figure
	fig.savefig(name + ".png")
Exemplo n.º 53
0
 def test_draw(self):
     N=self.G
     nx.draw_spring(N)
     plt.savefig("test.ps")
     nx.draw_random(N)
     plt.savefig("test.ps")
     nx.draw_circular(N)
     plt.savefig("test.ps")
     nx.draw_spectral(N)
     plt.savefig("test.ps")
     nx.draw_spring(N.to_directed())
     plt.savefig("test.ps")
     os.unlink('test.ps')
Exemplo n.º 54
0
	def fun_save_graph(self,graph,file_name,str_time):
		
		# prints the graph you hand it as a .png file in the directory specified by file_name

		import matplotlib
		import matplotlib.pyplot as plt
		import networkx as nx
		

		plt.figure()
		nx.draw_spring(graph,node_color='w',with_labels=True,node_size=1000,arrows=True)
		plt.savefig("out/" + str_time + "/%(pHolder_file_name)s" %dict(pHolder_file_name = file_name))
		
		print('Saved graph '+"out/" + str_time + "/%(file_name)s" %dict(file_name = file_name))
 def plot_induced_subgraphs(self):
     plt.figure(1)
     partition = self.find_partition()[1]
     communities = [partition[v] for v in partition]
     newGraph=self.G
     for community in communities:
         nx.subgraph(newGraph, [key for key in partition if partition[key]==community])
     node_color=[float(partition[v]) for v in partition]
     labels =  {}
     for node in newGraph.nodes():
         labels[node]= newGraph.node[node].get('name', '')
     nx.draw_spring(newGraph,node_color=node_color, labels=labels)
     plt.show()
     plt.savefig("C:\\Users\\Heschoon\\Dropbox\\ULB\\Current trends of artificial intelligence\\Trends_project\\graphs\\graph_induced.pdf")
 def draw_spring_communities(self, full_names='False', k=None, iterations=50, scale=1.0):
     partition = self.find_partition()[1]
     #colors = ['red', 'blue', 'green', 'cyan', 'magenta', 'yellow']
     #node_color=[colors[partition[v]] for v in partition]
     node_color=[float(partition[v])*2.0 for v in partition]
     if not(full_names):
         labels = self.compute_labels()
     else:
         labels =  {}
         for node in self.G.nodes():
             labels[node]= self.G.node[node].get('name', '')
     nx.draw_spring(self.G,node_color=node_color, labels=labels, k=k, iterations=iterations, scale=scale, cmap=plt.cm.hsv)
     plt.show()
     plt.savefig("C:\\Users\\Heschoon\\Dropbox\\ULB\\Current trends of artificial intelligence\\Trends_project\\graphs\\graph_spring.pdf")
Exemplo n.º 57
0
    def run_and_trace(self, name, workload, old=False, sync_period=0,
                      step_size=1, ignore_remaining=False, show_graph=False,
                      staleness=0):
        """
        Run and produce a log of the simulation for each timestep
        Convert an old format workload to new format if old=TRUE
        
        Dump the metrics, workload, and (if old-format) the converted
        new-format workload to JSON as files
        """
        filename = 'logs/' + name 
        dir = os.path.dirname(filename)
        try:
                os.stat(dir)
        except:
                os.mkdir(dir)

        f = open(filename + '.workload', 'w')
        print >>f, json.dumps(workload,sort_keys=True, indent=4)
        f.close()

        if (old):
            # log the converted old_to_new network graph
            workload = old_to_new(workload) 
            f = open(filename + '.newworkload', 'w')
            print >>f, json.dumps(workload,sort_keys=True, indent=4)
            f.close()
            metrics = self.run(workload, sync_period, step_size,
                               ignore_remaining, show_graph=show_graph,
                               staleness=staleness)
        else:
            metrics = self.run(workload, sync_period, step_size,
                               ignore_remaining, show_graph=show_graph,
                               staleness=staleness)

        f = open(filename + '.metrics', 'w')
        print >>f, json.dumps(metrics, sort_keys=True, indent=4)
        f.close()

        if show_graph:
            # log the network graph if not already drawn
            try:
                os.stat(filename + ".pdf")
            except:
                nx.draw_spring(self.graph)
                plt.savefig(filename + ".pdf")
                plt.close()

        return metrics
Exemplo n.º 58
0
def main():
    # Create a NetworkX graph object 
    gmail_graph=graphFromCSV("../email_analysis/email_graph.csv")

    # Draw entire graph
    full_graph=plt.figure(figsize=(10,10))
    nx.draw_spring(gmail_graph, arrows=False, node_size=50, with_labels=False)
    plt.savefig("../../../images/graphs/full_graph.png")
    
    # Draw [email protected]'s Ego graph
    ego_plot(gmail_graph, "*****@*****.**", "../../../images/graphs/ann9enigma_ego.png")

    # Create a lattice plot of all weakly connected components
    gmail_components=nx.weakly_connected_component_subgraphs(gmail_graph)
    lattice_plot(gmail_components, "../../../images/graphs/gmail_subgraphs.png")
Exemplo n.º 59
0
def draw_graph(D):
	D = D.to_undirected()
	plot.figure(figsize=(16,16))
	nx.draw_spring(D,
			node_color=[float(D.degree(v)) for v in D],
			#edge_color=[np.log(D[e1][e2]["weight"]+1) for e1,e2 in D.edges()],
			width=3,
			edge_cmap=plot.cm.Reds,			
			with_labels=True,
			cmap=plot.cm.Reds,
			node_size=1000,
			font_size=8,
			iterations=100000)
	plot.title("Spring Network Layout of %s" % D.name)
	plot.savefig("results/network_graphs/%s.png" % D.name)
	plot.close()