예제 #1
0
def plot_starlike(pathway):
    pylab.figure()
    nx.draw_circular(pathway, labels=pathway.labels)
    pylab.title(pathway.title)
    title = pathway.title.replace('/', '-') # TODO: which is the proper way to remove / in a filename?
    pylab.savefig('./plots/' + title + '.png')
    pylab.show()
예제 #2
0
    def plot_graphs(self):
        # draw lables
        # choose same layout as in drawing the rest of the graph
        pos_G=nx.circular_layout(self.g1)   # positions for all nodes for G (in this case circular)
        pos_H=nx.circular_layout(self.g2)   # positions for all nodes for H (in this case circular)
        labels_G = {}                 # create a dict with labels
        for item in self.g1.nodes():
            labels_G[item] = item

        labels_H = {}                 # create a dict with labels
        for item in self.g2.nodes():
            labels_H[item] = item

        # color-mapping via numpy
        # list of cmaps can be found here: http://matplotlib.org/examples/color/colormaps_reference.html
        # I chose this cmap because there are no dark colors in it so the labels stay readable regardless
        # the color of the label.
        plt.subplots_adjust(left=0,right=1,bottom=0,top=0.95,wspace=0.01,hspace=0.01)
        plt.subplot(121)
        plt.title("Graph G")
        nx.draw_circular(self.g1, cmap=plt.get_cmap('Set1'), node_color=self.nc1)
        nx.draw_networkx_labels(self.g1, pos_G, labels_G)

        plt.subplot(122)
        plt.title("Graph H")
        nx.draw_circular(self.g2, cmap=plt.get_cmap('Set1'), node_color=self.nc2)
        nx.draw_networkx_labels(self.g2, pos_H, labels_H)

        plt.show()
    def draw_transmission_graph(self, positions=False):
        """
		This method draws the transmission graph to the screen using 
		matplotlib.

		INPUTS:
		-	BOOLEAN: positions
				If False: the circular layout will be drawn.

				If True: nodes will be restricted in the x-axis.

		"""

        # Step 1: Guarantee that transmission_graph is made.
        transmission_graph = deepcopy(self.relabeled_transmission_graph)

        # Step 2: Draw the graph according to the time-restricted layout or
        # circular layout.
        if positions == False:
            nx.draw_circular(transmission_graph)

        if positions == True:
            if self.node_draw_positions == None:
                positions = dict()
                for pathogen in self.pathogens:
                    positions[str(pathogen)] = (pathogen.creation_time, randint(0, 20))

                self.node_draw_positions = positions

            nx.draw(transmission_graph, pos=self.node_draw_positions)
예제 #4
0
 def draw_helix_graph(self):
     nx.draw_circular(self.graph, node_color="lightyellow", node_size=1000)
     pos = nx.circular_layout(self.graph)
     edge_labels = dict([((u,v,),d['label'])
                         for u,v,d in self.graph.edges(data=True)])
     nx.draw_networkx_edge_labels(self.graph, pos, edge_labels=edge_labels)
     plt.title("Crossover Locations for Staples")
예제 #5
0
파일: FragGraph.py 프로젝트: jhooge/RAILIN
def plot_fragment_graph(G, labels=None, to_file=None, dpi=300):
    
#    try:
#        from networkx import graphviz_layout
#    except ImportError:
#        raise ImportError("This example needs Graphviz and either PyGraphviz or Pydot")
#    
#    if len(G.nodes()) == 0:
#        raise ValueError('No fragments to plot!')
#    
#    pos = nx.graphviz_layout(G, prog="dot")
    fig = pl.figure(figsize=(10, 10))
    node_size = 300
    nx.draw_circular(G)
#    nx.draw(G, pos,
#            with_labels=True,
#            alpha=0.5,
#            node_size=node_size)
    
    ## adjust the plot limits
#    offset = node_size / 2
#    xmax = offset + max(xx for xx, yy in pos.values())
#    ymax = offset + max(yy for xx, yy in pos.values())
#    xmin = min(xx for xx, yy in pos.values()) - offset
#    ymin = min(yy for xx, yy in pos.values()) - offset
#    pl.xlim(xmin, xmax)
#    pl.ylim(ymin, ymax)
    
    if to_file != None:
        filename = to_file.split('/')[-1]
        pl.savefig((filename + "_graph"), dpi=dpi)
    else:
        pl.show()
        return fig
예제 #6
0
def plot_network(res):
    """Plot network of multivariate TE between processes.

    Plot graph of the network of (multivariate) interactions between
    processes (e.g., multivariate TE). The function uses  the
    networkx class for directed graphs (DiGraph) internally.
    Plots a network and adjacency matrix.

    Args:
        res : dict
            output of multivariate_te.analyse_network()

    Returns:
        instance of a directed graph class from the networkx
        package (DiGraph)
    """
    try:
        res = res['fdr']
    except KeyError:
        print('plotting non-corrected network!')

    g = generate_network_graph(res)
    print(g.node)
    f, (ax1, ax2) = plt.subplots(1, 2)
    adj_matrix = nx.to_numpy_matrix(g)
    cmap = sns.light_palette('cadetblue', n_colors=2, as_cmap=True)
    sns.heatmap(adj_matrix, cmap=cmap, cbar=False, ax=ax1,
                square=True, linewidths=1, xticklabels=g.nodes(),
                yticklabels=g.nodes())
    ax1.xaxis.tick_top()
    plt.setp(ax1.yaxis.get_majorticklabels(), rotation=0)
    nx.draw_circular(g, with_labels=True, node_size=300, alpha=1.0, ax=ax2,
                     node_color='cadetblue', hold=True, font_weight='bold')
    plt.show()
    return g
 def draw_circular_communities(self):
     partition = self.find_partition()[1]
     node_color=[float(partition[v]) for v in partition]
     labels = self.compute_labels()
     nx.draw_circular(self.G,node_color=node_color, labels=labels)
     plt.show()
     plt.savefig("C:\\Users\\Heschoon\\Dropbox\\ULB\\Current trends of artificial intelligence\\Trends_project\\graphs\\graph_circular1.pdf")
예제 #8
0
def simulateBears(numYears):
  
  from BearClass import Bear
  from BearPopulationClass_tryNotN2 import BearPopulation
  import networkx as nx

  # Create the starting population
  # Make some "bear gods" to use as the parents for the progenitors
  beargod1 = Bear('bg1','M',None, None)
  beargod2 = Bear('bg2','M',None, None)
  beargod3 = Bear('bg3','F',None, None)
  adam = Bear('Adam', 'M',beargod1,beargod1)
  eve = Bear('Eve', 'F',beargod2,beargod2)
  mary = Bear('Mary', 'F',beargod3,beargod3)
  year = 0
  numBornInFirst100Years = 0
  
  # keep track of the number of males and females created
  #nMale = 1
  #nFemale = 2
  
  # Create a bear population from the progenitors
  progenitors = [adam, eve, mary]
  population = BearPopulation(progenitors)
  
  # Start stepping through time
  years = range(1,numYears+1)
  for year in years:
#    print "It is now the year: %s" %(year)
    # First things first: each bear gets a year older
    population.ageBears()
    # Now, what happens as the bears age
  
    # First, check if any bears died and add them to the part of the population
    # that has died
    population.checkForDead(year)
  #  for bear in population.allBears:
  #    print bear
    # Create a list of bears that are capable of procreating
    population.checkIfCanBang(year)
    numBornThisYear = population.generateOffspring(year)
    if year <= 100:
      numBornInFirst100Years += numBornThisYear
  #  nMale += newM
  #  nFemale += newF
    # Print the size of the population each year
#    print "Number of bears in population after %s years: %s" %(year, \
#          len(population.allBears) )
  #  for bear in population.canProcreate:
  #    print bear
  
  # Print the bear population
  #for bear in population.allBears:
  #  print bear
  
  print "Final Number of Bears after %i Years: %s" \
        %(numYears, len(population.allBears))
  if len(population.allBears) <= 1500:
    nx.draw_circular(population.tree)
  return numBornInFirst100Years, len(population.allBears)
예제 #9
0
파일: tass.py 프로젝트: lgadawski/tass
def draw_graph(g, out_filename):
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)

    plt.savefig(out_filename)
예제 #10
0
def plot_graph(G,circular=False):    
    #Desenha grafo e mostra na tela
    if not circular:
        nx.draw(G)
    else:
        nx.draw_circular(G)
    plt.show()
예제 #11
0
 def displayControlImportances(self,nocontrolconnectionmatrix, controlconnectionmatrix ):
     """This method will create a graph containing the 
     connectivity and importance of the system being displayed.
     Edge Attribute: color for control connection
     Node Attribute: node importance
     
     It's easier to just create the no control connecion matrix here...
     
     """
     
     ncG = nx.DiGraph()
     n = len(self.variablelist)
     for u in range(n):
         for v in range(n):
             if nocontrolconnectionmatrix[u,v] == 1:
                 ncG.add_edge(self.variablelist[v], self.variablelist[u])
     
     edgelistNC = ncG.edges()
     
     self.controlG = nx.DiGraph()
     
     for u in range(n):
         for v in range(n):
             if controlconnectionmatrix[u,v] == 1:
                 if (self.variablelist[v], self.variablelist[u]) in edgelistNC:
                     self.controlG.add_edge(self.variablelist[v], self.variablelist[u], controlloop = 0)
                 else:
                     self.controlG.add_edge(self.variablelist[v], self.variablelist[u], controlloop = 1)
     
     
     for node in self.controlG.nodes():
         self.controlG.add_node(node, nocontrolimportance = self.blendedrankingNC[node] , controlimportance = self.blendedranking[node])
     
     plt.figure("The Controlled System")
     nx.draw_circular(self.controlG)
예제 #12
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")
예제 #13
0
파일: fabfile.py 프로젝트: cheatas/LIA-P2P
def drawGraph(nodes,peers,root):
	
	global G
	

	#root = root.replace(" ", "")
	root = root[11:13]
	

	if root == "9:" or root == "9 ":
		root = "9" 


	print root
	print root[11:13]
	G.add_node(root)
	
	#G.add_node(root.replace(" ", ""))

	for x in peers:
		for y in nodes:
			if str(x) in y:
				peer = y[1][11:13]
				if peer == "9:" or peer == "9 ":
					peer = "9" 
				G.add_node(peer)
				G.add_edge(root,peer)
		
	#for x in (nodes):
	#	G.add_node(x[1])
	
	if(env.host_string == '145.100.97.62'):
		nx.draw_circular(G,with_labels=True,font_size=15,node_color='yellow',node_size=1000)
		print G.nodes()
		plt.show()	
예제 #14
0
파일: crawl.py 프로젝트: BrendanMartin/docs
    def test_build_networkx_graph(self):
        url = 'http://localhost:8181/'
        output = sys.stdout
        bs = bs4.BeautifulSoup(requests.get(url).content)
        links = list(extract_links(url, bs))
        g = build_networkx_graph(url, links, output=output)
        self.assertTrue(g)

        output = StringIO.StringIO()
        write_nxgraph_to_dot(g, output)
        output.seek(0)
        print(output.read())
        output.seek(0)
        self.assertTrue(output.read())

        output = StringIO.StringIO()
        write_nxgraph_to_json(g, output)
        output.seek(0)
        print(output.read())
        output.seek(0)
        self.assertTrue(output.read())
        output.seek(0)
        with open('./force/force.json','w') as f:
            f.write(output.read())

        import matplotlib.pyplot as plt
        import networkx
        networkx.draw_circular(g)
        plt.savefig("awesome.svg")
def draw_graph(graphDic, nodesStatus, imageName):
    node_colors = [] 
    #first writing the number of nodes 
    #nx.draw(G) 
    #select the color 
    newGraphDic = {} #without the status 
    for element in graphDic.keys():
        status = nodesStatus[element[0] - 1]
        if status == "INACTIVE":
            node_colors +=['white']
        if status == "ACTIVE":
            node_colors +=['red']
        if status == "SELECTED":
            node_colors +=['green']
    #generating the graph from the dictionary 
    G = nx.from_dict_of_lists(graphDic) 
    nx.draw_circular(G, node_color = node_colors, with_labels=True, node_size = 50)
    #G.text(3, 8, 'boxed italics text in data coords', style='italic', bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})
#    plt.legend(handles=[ green_patch])
#    nx.draw_networkx(G, node_color=node_colors, with_labels=True)
    
    #nx.draw_networkx(G) 
    #save the result  semiSparseRep 
    print "image name is" + imageName 
    plt.savefig(imageName);
예제 #16
0
파일: molecule.py 프로젝트: cjforman/pele
    def draw_graph(self, G, node_list=None, edge_colour='k', node_size=15, node_colour='r', graph_type='spring',
                   back_bone=None, side_chains=None, terminators=None):
        # determine nodelist
        if node_list is None:
            node_list = G.nodes()
        # determine labels
        labels = {}
        for l_atom in G.nodes_iter():
            labels[l_atom] = l_atom.symbol

        # draw graphs based on graph_type
        if graph_type == 'circular':
            nx.draw_circular(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'random':
            nx.draw_random(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spectral':
            nx.draw_spectral(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spring':
            nx.draw_spring(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'shell':
            nx.draw_shell(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                          edge_color=edge_colour, node_color=node_colour)
        # elif graph_type == 'protein':
        # self.draw_protein(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
        #                   edge_color=edge_colour, node_color=node_colour, back_bone, side_chains, terminators)
        else:
            nx.draw_networkx(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        plt.show()
예제 #17
0
파일: ggraph.py 프로젝트: gtfierro/ggraph
    def show(self, filename=''):
        """
        Uses the networkx/matplotlib.pyplot modules to graphically show what network
        was created. Nodes should have labels. Shows the resultant graph in a temporary window.
        If [filename] is provided, instead saves result in [filename]
        """
        try:
            import networkx
        except ImportError:
            print "Please install networkx via 'easy_install networkx', 'pip install networkx' or some other method."
            print "You will not have access to the full functionality of this module until then"
            sys.exit(1)

        try:
            import matplotlib.pyplot as plt
        except ImportError:
            print "Please install matplotlib via 'easy_install matplotlib', 'pip install matplotlib' or some other method."
            print "You will not have access to the full functionality of this module until then"
            sys.exit(1)

        string_edges = map(lambda x: "%s %s" % (x[0], x[1]), self.edge_list)
        graph = networkx.parse_edgelist(string_edges)
        networkx.draw_circular(graph,prog='neato',width=1,node_size=300,font_size=14,overlap='scalexy')
        if filename:
            plt.savefig(filename)
        else:
            plt.show()
예제 #18
0
def A11():
    graph = generate_erdos_renyi(20, 10)
    nx.draw_circular(graph, edge_color = [e[2]['t'] for e in graph.edges(data=True)], 
                                 edge_cmap=plt.get_cmap("gray"), edge_vmax = 20, node_size=100)
    plt.figure()
    graph= generate_erdos_renyi(20, 10, graph)
    nx.draw_circular(graph, edge_color = [e[2]['t'] for e in graph.edges(data=True)], 
                                 edge_cmap=plt.get_cmap("gray"), edge_vmax = 20, node_size=100)
예제 #19
0
    def show(self):
        """ Plot the graph"""

        # nx.draw(self.G)
        #nx.draw_graphviz(self.G)
        #nx.draw_shell(self.G)
        nx.draw_circular(self.G)
        plt.draw()
        plt.show()
예제 #20
0
def Graph():
    for k in range(30,100,10):
        print(k)
        G = nx.Graph()
        for i in range(1,k+1):
            for j in range(1,k+1):
                G.add_edge(i,j)

        nx.draw_circular(G, with_labels = False, node_size = 0)
        plt.show()
예제 #21
0
def _plot_graph(graph, axis, weights=None, display_edge_labels=True):
    """Plot graph using networkx."""
    pos = nx.circular_layout(graph)
    nx.draw_circular(graph, with_labels=True, node_size=600, alpha=1.0,
                     ax=axis, node_color='Gainsboro', hold=True, font_size=14,
                     font_weight='bold')
    if display_edge_labels:
        edge_labels = nx.get_edge_attributes(graph, weights)
        nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels,
                                     font_size=13)  # font_weight='bold'
예제 #22
0
def main():
    print("Graphing!")
    G = nx.Graph()
    G.add_nodes_from([1-3])
    G.add_edge(1, 2)

    nx.draw_random(G)
    nx.draw_circular(G)
    nx.draw_spectral(G)
    plt.show()
예제 #23
0
파일: demo.plot.py 프로젝트: gree2/hobby
def demo_save_fig():
    """demo_save_fig"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    plt.savefig("g.png")
예제 #24
0
def plotGraph(DG):
    '''Visualize network'''
    pmtkFigureFolder = os.environ['PMTKFIGUREFOLDER']
    import matplotlib.pyplot as plt
    plt.figure(figsize=(9,9))
    pos=networkx.spring_layout(DG,iterations=10)
    #networkx.draw(DG,pos,node_size=0,alpha=0.4,edge_color='r', font_size=16)
    networkx.draw_circular(DG)
    plt.savefig(os.path.join(pmktFigureFolder, "link_graph.pdf"))
    plt.show()
예제 #25
0
파일: demo.plot.py 프로젝트: gree2/hobby
def demo_write_doc():
    """demo_write_doc"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    nx.draw_graphviz(g)
    nx.write_dot(g, 'g.dot')
예제 #26
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")
예제 #27
0
 def printAll(self,tblIdx):    
     plt.clf()
     plt.figure(1,figsize=(10,10))        
     
     plt.xlim(-10,10)
     plt.ylim(-10,10)
     
     # with nodes colored by degree sized by population
     node_color=[float(self.relTree.degree(v)) for v in self.relTree]
     nx.draw_circular(self.relTree) 
     
     plt.savefig("xmlplan.png")    
예제 #28
0
def plot_bn(bns, labels, plot_label, ax=None):
    if ax is None:
        ax = plt.gca()

    idx = np.where(np.array(labels) == plot_label)[0][0]

    G = nx.DiGraph()
    for (p, q) in bns[idx][2].keys():
        G.add_edge(transform_label(p), transform_label(q))

    nx.draw_circular(G, node_color='w', with_labels=True, alpha=0.5,
            font_color=colorscheme['red'], ax=ax, node_size=0, font_size=16, node_shape="s")
def circular_connections(n_t, ne, excitatory_synapse, inhibitory_synapse):
    H = range(1, n_t)
    G = nx.Graph()
    G.add_nodes_from(H)
    for i, j in zip(excitatory_synapse.i, excitatory_synapse.j):
        G.add_edge(i+1, j+1)
    for g, k in zip(inhibitory_synapse.i, inhibitory_synapse.j):
        G.add_edge(g+ne+1, k+1)
    pl = nx.average_shortest_path_length(G)
    nx.draw_circular(G)
    title('sds')
    return pl
def plot_network_return_median(transaction_set, pause_time=0):
    pairs_in_window = [(t, a) for (time, (t, a)) in transaction_set]
    transaction_graph = networkx.Graph(pairs_in_window)
    networkx.draw_circular(transaction_graph)
    plot_tool.show()
    if pause_time > 0:
        plot_tool.pause(pause_time)
    plot_tool.close()

    degrees = [degree[1] for degree in transaction_graph.degree()]
    median = "%.2f\n" % statistics.median(degrees)
    return median
예제 #31
0
# coding: utf-8

# In[2]:


import matplotlib.pyplot as plt
import networkx as nx

G = nx.karate_club_graph()
print("Node Degree")
#for v in G:
 #   print('%s %s' % (v, G.degree(v)))
get_ipython().run_line_magic('matplotlib', 'inline')
plt.figure(1)
nx.draw_circular(G, with_labels=True)
plt.show()
plt.cla()
nx.draw_circular(G, with_labels=True)
plt.show() 


# In[2]:


import tensorflow as tf
weights = tf.Variable(tf.random_normal([300, 200], stddev=0.5),
name="weights")


# In[3]:
예제 #32
0
    if 'digraph' in graphType:
        graph = nx.DiGraph()
    else:
        graph = nx.Graph()


graphType = input('Please specify graph type(graph/digraph): >>')
process_graph_type(graphType)
while whileBool:
    print('Enter command. \'help\' for help')
    raw_input = input('>>')
    process_raw_input(raw_input)
    if successfulCommand:
        successfulCommand = False
        nx.draw_circular(graph,
                         node_color='red',
                         node_size=1000,
                         with_labels=True)
        # labels = nx.get_edge_attributes(graph, 'weight')
        # nx.draw_networkx_edge_labels(graph, edge_labels=labels)
        plt.ion()
        plt.pause(0.001)
        if requires_saving:
            requires_saving = False
            now = datetime.datetime.now()
            plt.savefig(
                str(pathlib.Path(__file__).parent.parent.absolute()) +
                '/images/' + filename + now.strftime("-%m/%d/%Y-%H:%M:%S-") +
                '.png')
        plt.show()
        plt.clf()
예제 #33
0
plt.figure(figsize=(14, 14))

plt.subplot(231)
plt.title('Grafo Erdos-Renyi', fontsize=20)
nx.draw_random(G1,
               node_color='blue',
               node_size=200,
               with_labels=False,
               alpha=0.8)

plt.subplot(232)
plt.title('Grafo Watts-Strogatz', fontsize=20)
nx.draw_circular(G2,
                 node_color='green',
                 node_size=200,
                 with_labels=False,
                 alpha=0.8)

plt.subplot(233)
plt.title('Grafo Barabasi-Albert', fontsize=20)
nx.draw_spring(G3,
               node_color='orange',
               node_size=200,
               with_labels=False,
               alpha=0.8)

plt.subplot(234)
plt.title('Grafo Completo', fontsize=20)
nx.draw_shell(G4,
              node_color='deeppink',
예제 #34
0
    iter += 1

for x in file:  #Looping on my file line by line
    edges = x.split(" ")  #Spliting my line to (node , node , weight)
    MyGraph.add_weighted_edges_from([
        (int(edges[0]), int(edges[1]), int(edges[2]))
    ])  #Adding my edges to my graph

degree = N.degree_centrality(
    MyGraph)  #List degree centrality of all nodes in [degree]
max_degree = degree[0]

for x in degree:  #serching in my degree list about the max degree
    if max_degree < degree[x]:
        max_degree = degree[x]

for x in degree:  #Pushing green or blue in the color map list depending on the max degree
    if max_degree == degree[x]:
        color_map.append('green')
    else:
        color_map.append('blue')

labels = N.draw_networkx_labels(
    MyGraph, pos=N.circular_layout(MyGraph))  #Writing labels on my nodes
edge_labels = N.draw_networkx_edge_labels(
    MyGraph, pos=N.circular_layout(MyGraph))  #Writing labels on my edges
N.draw_circular(
    MyGraph, node_color=color_map
)  #Drawing my graph in circular form with colors in color_map list
plt.show()
Mapa.add_weighted_edges_from([(1,2,2),(2,3,4),(3,4,7),(4,5,3),(5,1,6),(1,3,9),
                              (2,4,3),(2,5,8),(1,4,3),(3,5,3)])
'''
cidades = []
qtd_cidade = 10
for i in range(1, qtd_cidade+1):
    cidades.append(i)

Mapa = nx.Graph()
Mapa.add_nodes_from(cidades)
for i in range(1, qtd_cidade+1):
    for j in range(1, qtd_cidade+1):
        if i > j:  # Pra não percorrer a mesma aresta duas vezes
            Mapa.add_edge(i,j, weight=random.randint(0, 50))

nx.draw_circular(Mapa,with_labels=True,font_weight='bold')
nx.draw_networkx_edge_labels(Mapa, pos=nx.circular_layout(Mapa))
plt.show()


def pop_inic(tam_pop, tam_cromo):
    '''Gera populacao inical. Recebe o tamanho da populacao e do cromossomo.'''
    cromossomos = []  # Lista de caminhos
    cidades = []  # Lista com nomes das cidades
    for i in range(1,tam_cromo+1):  # Nomeia cidades e 1 a tam_cromo+1
        cidades.append(i)
        
    for i in range(tam_pop):  # Cria lista de cromossomos
        caminho = random.sample(cidades, tam_cromo)
        while(caminho in cromossomos):  # while garante que nao ha dois caminhos iguais na populacao
            caminho = random.sample(cidades, tam_cromo)
예제 #36
0
"""
Creating a standard graph and displaying it along with the its matrix
"""

import matplotlib.pylab as plt
import networkx as nx
import matplotlib.cm

if __name__ == '__main__':
    G = nx.barabasi_albert_graph(30, 5)
    plt.figure('Graph')
    nx.draw_circular(G,
                     node_color=range(len(G)),
                     cmap=matplotlib.cm.jet,
                     with_labels=True)
    plt.figure('Graph Matrix')
    plt.imshow(nx.to_numpy_matrix(G))

    plt.show()
        result_line = ''
        result_line += graph_filename + delimeter
        result_line += str(graph_n) + delimeter
        result_line += str(graph_m) + delimeter
        result_line += str(graph_degree_variance) + delimeter
        result_line += str(graph_diameter) + delimeter
        result_line += str(graph_average_distance) + delimeter
        result_line += str(graph_edge_betweenness_max_value -
                           graph_edge_betweenness_min_value) + delimeter
        result_line += str(graph_edge_betweenness_max_value)
        if (with_avg_files):
            result_line += delimeter + str(graph_curve_average)
        result_line += '\n'
        result_table += result_line
        if (draw_topos):
            nx.draw_circular(graph_list[index])
            plt.savefig(result_drawed_graph_path + graph_filename)
            plt.clf()
#             print "Drawing graph",str(index+1-index_init)+'/'+str(index_end-index_init)+'.'
        label_index += 1

    result_file = open(result_statistics_path + result_statistics_filename,
                       'w+')
    result_file.write(result_table)
    result_file.close()
elif (draw_topos):
    for index in range(index_init - 1, index_end):
        graph_filename = 'n' + str(graph_n) + '_g' + str(label_index) + '.png'
        nx.draw_circular(graph_list[index])
        plt.savefig(result_drawed_graph_path + graph_filename)
        plt.clf()
nonzero = np.count_nonzero(weight_matrix)
weight_matrix[weight_matrix < 0.99] = 0.0
new_nonzero = np.count_nonzero(weight_matrix)

print '\n'
print nonzero, new_nonzero, new_nonzero / float(nonzero)
print '\n'

weight_matrix[weight_matrix > 0.0] = 1

G = nx.Graph(weight_matrix)

plt.figure(figsize=(18.5, 10))
nx.draw_circular(G,
                 node_color='g',
                 edge_color='#909090',
                 edge_size=1,
                 node_size=10)
plt.axis('equal')

plt.show()

plt.figure(figsize=(18.5, 10))
nx.draw_spectral(G,
                 node_color='g',
                 edge_color='#909090',
                 edge_size=1,
                 node_size=10)
plt.axis('equal')

plt.show()
예제 #39
0
no_of_edges=realnodes*(realnodes-1)/2
it=0
i=0
while i<50:
j=i+1
while j<50:
if it>no_of_edges:
i=100
j=100
else:
G.add_edge(i,j)
it=it+1
j=j+1
i=i+1
#drawing the graph
nx.draw_circular(G,with_labels=1)
plt.show()
print("Number of nodes:",realnodes)
print("Number of edges:",no_of_edges)
#finding average path length
i=0
x=0
apl=0
while i<49:
j=i+1
while j<50:
try:
try: #sum stores the sum of geodesics and num stores the number of nodes having geodesics
apl=apl+len(nx.shortest_path(G,i,j))
except networkx.exception.NetworkXNoPath:
apl=apl+0
    print(
        'Profit of tour found by the solver is {}, cost of it is {}, and cost computed by us for verification is {} '
        .format(round(prob.value, 2), cost.value, round(verified_cost, 2)))
    print(
        'Time taken to solve the problem instance after formulation is {} seconds'
        .format(round(prob.solver_stats.solve_time, 2)))

    color_map = ['red'] * num_nodes
    color_map[0] = 'green'

    pos = nx.circular_layout(g)
    nodeval = nx.get_node_attributes(g, 'value')
    nx.draw_circular(g,
                     with_labels=True,
                     node_color=color_map,
                     node_size=1000,
                     labels=nodeval)
    labels = nx.get_edge_attributes(g, 'weight')
    nx.draw_networkx_edge_labels(g,
                                 pos,
                                 edge_labels=labels,
                                 width=20,
                                 edge_color='b')
    plt.savefig('foo.png')
    plt.title('Time horizon {}'.format(total_time))
    plt.show()
#print(cost_matrix)
#print(x.value)
#print(score_vector)
예제 #41
0
print('The data type of bow matrix {}'.format(type(cv_matrix)))
print('Shape of the matrix {}'.format(cv_matrix.get_shape))
print('Size of the matrix is: {}'.format(sys.getsizeof(cv_matrix)))
print(cv.get_feature_names())
print(cv_matrix.toarray())

normal_matrix = TfidfTransformer().fit_transform(cv_matrix)
print(normal_matrix.toarray())

print(normal_matrix.T.toarray)
res_graph = normal_matrix * normal_matrix.T
# plt.spy(res_graph)

nx_graph = nx.from_scipy_sparse_matrix(res_graph)
nx.draw_circular(nx_graph)
print('Number of edges {}'.format(nx_graph.number_of_edges()))
print('Number of vertices {}'.format(nx_graph.number_of_nodes()))
# plt.show()
print('The memory used by the graph in Bytes is: {}'.format(
    sys.getsizeof(nx_graph)))

ranks = nx.pagerank(nx_graph)

# analyse the data type of ranks
print(type(ranks))
print('The size used by the dictionary in Bytes is: {}'.format(
    sys.getsizeof(ranks)))

# print the dictionary
for i in ranks:
예제 #42
0
plt.plot([0,1],[0,1],'r--')
plt.xlim([-0.1,1.2])
plt.ylim([-0.1,1.2])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()

fpr, tpr, thresholds = metrics.roc_curve(labels, trLabels)
print metrics.auc(fpr, tpr)
'''
'''
 Features Analysis w.r.t Spam/Non-Spam
 1. Load features as Pandas Dataframe


spamMap = Commons.getLabelsDictionary(datasetFilePath + CONFIG_FILE["training-file"], NUM_NODES)

obviousFeatures = pd.read_csv(datasetFilePath + CONFIG_FILE["obvious-features-file"])
# Commons.plotFeatureForBothLabels(spamMap, obviousFeatures['length_of_hostname'])

contentFeatures = pd.read_csv(datasetFilePath + CONFIG_FILE["content-features-file"])
'''
'''
Graph Plot
pos = nx.circular_layout(graph)
nx.draw_circular(graph)
labels = {i : i + 1 for i in graph.nodes()}
nx.draw_networkx_labels(graph, pos, labels, font_size=15)
plt.show()
'''
예제 #43
0
                    'George Clooney': ['Brad Pitt', 'Samuel L. Jackson', 'Kevin Spacey', 'Bruce Willis', 'Gary Oldman', 'Matt Damon', 'Jared Leto', 'John Travolta', 'John C. Reilly'],
                    'Sean Connery': ['Kevin Costner', 'Nicolas Cage', 'Morgan Freeman', 'Harrison Ford', 'Matt Damon', 'Alec Baldwin'],
                    'Gary Oldman': ['Kevin Costner', 'Brad Pitt', 'Samuel L. Jackson', 'Tommy Lee Jones', 'Kevin Spacey', 'Morgan Freeman', 'Bruce Willis', 'Heath Ledger', 'Christian Bale', 'George Clooney', 'Harrison Ford', 'Liam Neeson', 'Kevin Bacon', 'John C. Reilly'],
                    'Harrison Ford': ['Brad Pitt', 'Clint Eastwood', 'Mel Gibson', 'Samuel L. Jackson', 'Tommy Lee Jones', 'Kevin Spacey', 'Sean Connery', 'Gary Oldman', 'Liam Neeson', 'Will Smith', 'Alec Baldwin', 'John C. Reilly'],
                    'Matt Damon': ['Tom Hanks', 'Kevin Costner', 'Brad Pitt', 'Clint Eastwood', 'Leonardo DiCaprio', 'Tommy Lee Jones', 'Kevin Spacey', 'Morgan Freeman', 'Bruce Willis', 'Johnny Depp', 'Heath Ledger', 'George Clooney', 'Sean Connery', 'Will Smith', 'Robin Williams', 'John Travolta', 'Alec Baldwin'],
                    'Liam Neeson': ['Clint Eastwood', 'Leonardo DiCaprio', 'Mel Gibson', 'Samuel L. Jackson', 'Morgan Freeman', 'Russell Crowe', 'Christian Bale', 'Gary Oldman', 'Harrison Ford', 'Will Smith', 'John C. Reilly'],
                    'Will Smith': ['Tommy Lee Jones', 'Nicolas Cage', 'Russell Crowe', 'Harrison Ford', 'Matt Damon', 'Liam Neeson', 'Jared Leto', 'John Travolta', 'Alec Baldwin', 'John C. Reilly'],
                    'Robin Williams': ['Brad Pitt', 'Mel Gibson', 'Kevin Spacey', 'Christian Bale', 'Matt Damon', 'John Travolta'],
                    'Kevin Bacon': ['Tom Hanks', 'Kevin Costner', 'Brad Pitt', 'Tommy Lee Jones', 'Johnny Depp', 'Tom Cruise', 'Gary Oldman', 'Alec Baldwin', 'John C. Reilly'],
                    'Jared Leto': ['Brad Pitt', 'Nicolas Cage', 'Christian Bale', 'George Clooney', 'Will Smith', 'John Travolta', 'John C. Reilly'],
                    'John Travolta': ['Clint Eastwood', 'Leonardo DiCaprio', 'Samuel L. Jackson', 'Kevin Spacey', 'Nicolas Cage', 'Bruce Willis', 'Johnny Depp', 'Tom Cruise', 'George Clooney', 'Matt Damon', 'Will Smith', 'Robin Williams', 'Jared Leto', 'John C. Reilly'],
                    'Alec Baldwin': ['Leonardo DiCaprio', 'Kevin Spacey', 'Bruce Willis', 'Tom Cruise', 'Sean Connery', 'Harrison Ford', 'Matt Damon', 'Will Smith', 'Kevin Bacon', 'John C. Reilly'],
                    'John C. Reilly': ['Kevin Costner', 'Leonardo DiCaprio', 'Samuel L. Jackson', 'Tommy Lee Jones', 'Johnny Depp', 'Tom Cruise', 'George Clooney', 'Gary Oldman', 'Harrison Ford', 'Liam Neeson', 'Will Smith', 'Kevin Bacon', 'Jared Leto', 'John Travolta', 'Alec Baldwin'],
                   })

nx.draw_circular(network, iteration = 9999, node_size = 1000, with_labels = True, node_color="white")
plt.show()

print ('Global cluster coefficient of network: ' + str(nx.average_clustering(network)))
nx.clustering(network)



# ## Most Central Actor
# 
# The "most central" actor in my network is **George Clooney** with a cluster coefficient of **.61**.
# 
# ## Actor's Cluster Coefficient By Hand
# 
# The five actors that I have chosen to calculate their cluster coefficients by hand are: **Tom Hanks**, **Mel Gibson**, **Russell Crowe**, **Robin Williams** and **Heath Ledger**.
# 
예제 #44
0
from counting import *
from graphical_models import *

def net_to_digraph(net):
	g = nx.DiGraph()
	g.add_nodes_from(net.iter_nodes())
	g.add_edges_from(net.iter_edges())

	return g

if __name__ == '__main__':
	from models import erdos_renyi
	import matplotlib.pyplot as plt

	G = erdos_renyi(100,0.01)
	DG = net_to_digraph(G)

	fig = plt.figure()
	fig.add_subplot(121)
	nx.draw_random(DG)
	fig.add_subplot(122)
	nx.draw_circular(DG)	
	plt.show()
	plt.close()

	from models import m_deep_bistable
	net = m_deep_bistable(7, 0.96)
	g = net_to_digraph(net)
	nx.draw(g)
	plt.show()
	plt.close()
예제 #45
0
import networkx as nx
import matplotlib.pyplot as plt

if __name__ == '__main__':
    amount = range(20)

    G = nx.Graph()
    G.add_nodes_from(amount)

    for x in amount:
        for y in amount:
            G.add_edges_from([(x, y)])

    nx.draw_circular(G, node_color='y', edge_color='#909090', node_size=500)

    plt.axis('equal')
    plt.show()
예제 #46
0
                    fm.add_edge(feature_list[j],
                                feature_list[i],
                                rel='OPTIONAL')

#print(*fm.edges.data(),sep="\n")

#display of original call graph

lbls = {}
for i in G:
    lbls[i] = G.nodes[i]['value']
pos = nx.circular_layout(G)

nx.draw_circular(G,
                 node_size=2000,
                 node_color='pink',
                 node_shape='o',
                 width=2.0,
                 with_labels=False)
nx.draw_networkx_labels(G, pos, lbls, font_size=10)
plt.axis('off')
plt.show()

#display of feature model graph

labels = {}
for i in fm:
    labels[i] = fm.nodes[i]['value']
pos = nx.circular_layout(fm)

nx.draw_circular(fm,
                 node_size=2000,
예제 #47
0
#file_to_write = open("Anaheim_edge_list.txt", "w")
#
#nodes = {}
#count = 1
#for line_a in file:
#    k = line_a.strip().split('\t')
#    #print
#    file_to_write.write(k[0] + '\t' + k[1] + '\n')
#
#file_to_write.close()
#file.close()

graph = nx.read_edgelist(file_to_open)

nx.draw_circular(graph, node_size=1)
plt.savefig("Transportation-Networks-Data/Anaheim/Anaheim_draw_circular",
            dpi=400)
plt.show()

nx.draw_kamada_kawai(graph, node_size=1)
plt.savefig("Transportation-Networks-Data/Anaheim/Anaheim_draw_kamada_kawai",
            dpi=400)
plt.show()

nx.draw_random(graph, node_size=1)
plt.savefig("Transportation-Networks-Data/Anaheim/Anaheim_draw_random",
            dpi=400)
plt.show()

nx.draw_spectral(graph, node_size=1)
예제 #48
0
        #Ignore the lower triangle to avoid duplicating entries
        for j in range(i, size):
            if matrix[i][j] == 1:
                edge = [i, j]  #Obtain the node pair
                edges.append(edge)
    return edges


#First initialise an empty graph
g = nx.Graph()
#Now get the adjacency matrix
matrix = create_random_graph_p(size, probability)
#Parse the edges from the adjacency
edges = get_edges_from_matrix(matrix)
#Construct the graph
g.add_nodes_from(range(size))
g.add_edges_from(edges)

#Output adjacency matrix and list of edges (node pairs)
#print(matrix,"\n")
#print(edges,"\n")
print("Number of edges: ", len(edges), "( Max:", (size * (size - 1) / 2), ")")

#Draw the graphs
plt.figure(figsize=(12, 12))
colour = [0.7, 0.7, 1, 1]
plt.subplot(221)
nx.draw(g, with_labels=True, node_color=colour)
plt.subplot(222)
nx.draw_circular(g, with_labels=True, node_color=colour)
plt.show()
예제 #49
0
def draw_graph(g):
    "Display an edge-weighted graph."
    labels = nx.get_edge_attributes(g, 'weight')
    nx.draw_networkx_edge_labels(g, nx.circular_layout(g), edge_labels=labels)
    nx.draw_circular(g, with_labels=True)
예제 #50
0
    required_by = [
        int(num) for line in required_regex.findall(data)
        for num in line.split(', ')
    ]
    for num in required_by:
        all_required_by.append((origin, num))

edges = list(G.edges)

for (num, origin) in all_required_by:
    edge = (origin, num)
    if edge not in edges:
        print('Missing requirement from {} to {}!'.format(origin, num))
        sys.exit(1)

print('Scanning for possible cycles...')

cycles = list(nx.algorithms.cycles.simple_cycles(G))

if len(cycles) == 0:
    print('No cycles!')
else:
    print('Found cycles!')
    print(cycles)
    sys.exit(1)

print('Drawing dependency graph...')

nx.draw_circular(G, with_labels=True, font_weight='bold', node_size=500)
plt.savefig('deps.png')
예제 #51
0
#########################################################################
# Similarity matrices can be converted to and from Distance matrices using `.similarity_to_distance()` and `.distance_to_similarity()`.

dist.distance_to_similarity(metric="correlation").plot()

#########################################################################
# Multidimensional Scaling
# ------------------------
#
# We can perform additional analyses on distance matrices such as multidimensional scaling. Here we provide an example to create a 3D multidimensional scaling plot of our data to see if the on and off matrices might naturally group together.

dist = data.distance(metric="correlation")
dist.labels = ["On"] * 5 + ["Off"] * 5 + ["On"] * 5
dist.plot_mds(n_components=3)

#########################################################################
# Graphs
# ------
#
# Adjacency matrices can be cast to networkx objects using `.to_graph()` if the optional dependency is installed. This allows any graph theoretic metrics or plots to be easily calculated from Adjacency objects.

import networkx as nx

dat = Adjacency(m1 + m2 + m3, matrix_type="similarity")
g = dat.to_graph()

print("Degree of each node: %s" % g.degree())

nx.draw_circular(g)
예제 #52
0
import re

n=30
m=4
probability = 0.7
G = nx.barabasi_albert_graph(n, m)

start_node = numpy.random.choice(list(G.nodes()))
I = []
R = []  
I = I + [start_node]
time = 1


plt.cla()
nx.draw_circular(G,node_color='g')
nx.draw_circular(G,nodelist=I,node_color='r',alpha=1)
nx.draw_circular(G,nodelist=R,node_color='b',alpha=1)
plt.savefig(r'C:\Users\micha\Desktop\Programs\DiffProcess\list5\barabasialbert\\'+str(0)+'.png', dpi=100)

time = 1
while len(I) != 0:
    newI = []
    for i in range(len(I)):
        infecting = I[i]
        S = list(set(G.neighbors(infecting))-set(I)-set(R))
        for k in S:
            if k not in newI:
                if random.random() < probability:
                    if k not in newI:
                        newI.append(k)    
예제 #53
0
def plot(G,
         node_color=None,
         node_label=None,
         node_size=100,
         node_size_scale=[25, 200],
         alpha=0.8,
         font_size=18,
         cmap='Set1',
         width=40,
         height=30,
         pos=None,
         filename=None,
         title=None,
         methodtype='default',
         verbose=3):
    # https://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html
    config = dict()
    config['filename'] = filename
    config['width'] = width
    config['height'] = height
    config['verbose'] = verbose
    config['node_size_scale'] = node_size_scale

    if verbose >= 3: print('[NETWORK] Creating network plot')

    if 'pandas' in str(type(node_size)):
        node_size = node_size.values

    #scaling node sizes
    if config['node_size_scale'] != None and 'numpy' in str(type(node_size)):
        if verbose >= 3: print('[NETWORK] Scaling node sizes')
        node_size = minmax_scale(node_size,
                                 feature_range=(node_size_scale[0],
                                                node_size_scale[1]))

    # Node positions
#    if isinstance(pos, type(None)):
#        pos=nx.spring_layout(G)

#    if isinstance(node_label, type(None)):
#        node_label=[*G.nodes])

    fig = plt.figure(figsize=(config['width'], config['height']))

    # Make the graph
    if methodtype == 'circular':
        nx.draw_circular(G,
                         labels=node_label,
                         node_size=node_size,
                         alhpa=alpha,
                         node_color=node_color,
                         cmap=cmap,
                         font_size=font_size,
                         with_labels=True)
    elif methodtype == 'kawai':
        nx.draw_kamada_kawai(G,
                             labels=node_label,
                             node_size=node_size,
                             alhpa=alpha,
                             node_color=node_color,
                             cmap=cmap,
                             font_size=font_size,
                             with_labels=True)
    else:
        nx.draw_networkx(G,
                         labels=node_label,
                         pos=pos,
                         node_size=node_size,
                         alhpa=alpha,
                         node_color=node_color,
                         cmap=cmap,
                         font_size=font_size,
                         with_labels=True)
#        nx.draw_networkx(G, pos=pos, node_size=node_size, alhpa=alpha, node_color=node_color, cmap=cmap, font_size=font_size)

    plt.title(title)
    plt.grid(True)
    plt.show()

    # Savefig
    if not isinstance(config['filename'], type(None)):
        if verbose >= 3: print('[NETWORK.plot] Saving figure')
        plt.savefig(config['filename'])

    return (fig)
예제 #54
0
from pip import main
with open('requirements.txt', 'r') as f:
    for line in f:
        print(line)
        main(('install ' + line).split(' '))
import networkx
from pylab import *
from numpy import *
from izhikevich import Izikevich
n = 100
k = 30
p = .6

G = networkx.random_graphs.connected_watts_strogatz_graph(n, k, p)
fig, ax = subplots()
networkx.draw(G, pos = networkx.draw_circular(G))
print(G.edges())
show()

# %%
# - make graph
# - for every node in the graph make a neural object with random values
# - simulate and record the spikes

def createVertices(G, v = -70, u = -65, a = .02, b = .2, c = -65, d = 2):
    vertices = {}
    for node in G.nodes():
        v = random.rand() * -70 + 50
        u = random.rand() * -65 + 15
        d = random.rand() * 2
        vertices[node] = Izikevich(v, u, a, b, c, d)
        d['weight'] = 1. / H.in_degree(u)
    np.savetxt(fout1, nx.adjacency_matrix(H), '%5.3f')
    np.savetxt(fout2, nx.adjacency_matrix(H), '%5.3f')
    nx.draw(H, 'b')
    pylab.savefig('./Input/Network_Scale_Free_Directed.ps')
    fout1.close()
    fout2.close()

if (Which_network == 'SMALL_WORLD'):
    G = nx.watts_strogatz_graph(nNodes, 2, p=0.0, seed=1)
    H = G.to_directed()
    for u, v, d in H.edges(data=True):
        d['weight'] = 1. / H.in_degree(u)
    np.savetxt(fout1, nx.adjacency_matrix(H), '%3.1f')
    np.savetxt(fout2, nx.adjacency_matrix(H), '%3.1f')
    nx.draw_circular(G)
    #nx.draw(H)
    pylab.savefig('./Input/Network_Small_World_%s.ps' % initial_nodes)
    fout1.close()
    fout2.close()
    pylab.close()

if (Which_network == 'SMALL_WORLD_CONNECTED'):
    G = nx.connected_watts_strogatz_graph(nNodes, 2, p=0.2, seed=None)
    H = G.to_directed()
    for u, v, d in H.edges(data=True):
        d['weight'] = 1. / H.in_degree(u)
    np.savetxt(fout1, nx.adjacency_matrix(H), '%5.3f')
    np.savetxt(fout2, nx.adjacency_matrix(H), '%5.3f')
    nx.draw(H)
    pylab.savefig('./Input/Network_Small_World_Connected.ps')
weights_fl = [graph_fl[u][v]['weight'] for u, v in edges_fl]

edges_plen = graph_plen.edges()
colors_plen = [graph_plen[u][v]['color'] for u, v in edges_plen]
weights_plen = [graph_plen[u][v]['weight'] for u, v in edges_plen]

edges_nh = graph_nh.edges()
colors_nh = [graph_nh[u][v]['color'] for u, v in edges_nh]
weights_nh = [graph_nh[u][v]['weight'] for u, v in edges_nh]

edges_hlim = graph_hlim.edges()
colors_hlim = [graph_hlim[u][v]['color'] for u, v in edges_hlim]
weights_hlim = [graph_hlim[u][v]['weight'] for u, v in edges_hlim]

edges_src = graph_src.edges()
colors_src = [graph_src[u][v]['color'] for u, v in edges_src]
weights_src = [graph_src[u][v]['weight'] for u, v in edges_src]

nx.draw_circular(graph_tc, node_color='blue', node_size=10000, font_color='w', edge_color=colors_tc, width=weights_tc, with_labels=True, label='graph_tc')
plt.show()
nx.draw_circular(graph_fl, node_color='red', node_size=10000, font_color='w', edge_color=colors_fl, width=weights_fl, with_labels=True, label='graph_fl')
plt.show()
nx.draw_circular(graph_plen, node_color='yellow', node_size=10000, font_color='w', edge_color=colors_plen, width=weights_plen, with_labels=True, label='graph_plen')
plt.show()
nx.draw_circular(graph_nh, node_color='green', node_size=10000, font_color='w', edge_color=colors_nh, width=weights_nh, with_labels=True, label='graph_nh')
plt.show()
nx.draw_circular(graph_hlim, node_color='purple', node_size=10000, font_color='w', edge_color=colors_hlim, width=weights_hlim, with_labels=True, label='graph_hlim')
plt.show()
nx.draw_circular(graph_src, node_color='orange', node_size=10000, font_color='w', edge_color=colors_src, width=weights_src, with_labels=True, label='graph_tc')
plt.show()
예제 #57
0
kanas = set()
edges = {}
max_weight = 0
for entry in entries:
    (first, last) = shiritori_parse(entry.japanese)
    kanas = kanas | {first, last}
    if (first, last) in edges.keys():
        edges[(first, last)] = edges[(first, last)] + 1
    else:
        edges[(first, last)] = 1

    if edges[(first, last)] > max_weight:
        max_weight = edges[(first, last)]

kanas = sorted(kanas)

edges = {k: v for k, v in sorted(edges.items(), key=lambda item: item[1])}
edge_colors = [color_input(val / max_weight) for val in edges.values()]

edges = [key for key in edges.keys()]

G = nx.DiGraph()
G.add_nodes_from(kanas)
G.add_edges_from(edges)

nx.draw_circular(G, with_labels=True, edge_color=edge_colors, width=0.75)
plt.rcParams['font.family'] = "sans-serif"
plt.rcParams['font.sans-serif'] = "MS Gothic"
plt.show()
예제 #58
0
plt.show()

# command if you are not using matplotlib in interactive mode (see
# [Matplotlib FAQ](http://matplotlib.org/faq/installing_faq.html#matplotlib-compiled-fine-but-nothing-shows-up-when-i-use-it)
# ).

options = {
    'node_color': 'black',
    'node_size': 100,
    'width': 3,
}
plt.subplot(221)
nx.draw_random(G, **options)
plt.subplot(222)
nx.draw_circular(G, **options)
plt.subplot(223)
nx.draw_spectral(G, **options)
plt.subplot(224)
nx.draw_shell(G, nlist=[range(5, 10), range(5)], **options)

# You can find additional options via `draw_networkx()` and
# layouts via `layout`.
# You can use multiple shells with `draw_shell()`.

G = nx.dodecahedral_graph()
shells = [[2, 3, 4, 5, 6], [8, 1, 0, 19, 18, 17, 16, 15, 14, 7],
          [9, 10, 11, 12, 13]]
nx.draw_shell(G, nlist=shells, **options)

# To save drawings to a file, use, for example
예제 #59
0
파일: molecule.py 프로젝트: cjforman/pele
    def draw_graph(self,
                   G,
                   node_list=None,
                   edge_colour='k',
                   node_size=15,
                   node_colour='r',
                   graph_type='spring',
                   back_bone=None,
                   side_chains=None,
                   terminators=None):
        # determine nodelist
        if node_list is None:
            node_list = G.nodes()
        # determine labels
        labels = {}
        for l_atom in G.nodes_iter():
            labels[l_atom] = l_atom.symbol

        # draw graphs based on graph_type
        if graph_type == 'circular':
            nx.draw_circular(G,
                             with_labels=True,
                             labels=labels,
                             node_list=node_list,
                             node_size=node_size,
                             edge_color=edge_colour,
                             node_color=node_colour)
        elif graph_type == 'random':
            nx.draw_random(G,
                           with_labels=True,
                           labels=labels,
                           node_list=node_list,
                           node_size=node_size,
                           edge_color=edge_colour,
                           node_color=node_colour)
        elif graph_type == 'spectral':
            nx.draw_spectral(G,
                             with_labels=True,
                             labels=labels,
                             node_list=node_list,
                             node_size=node_size,
                             edge_color=edge_colour,
                             node_color=node_colour)
        elif graph_type == 'spring':
            nx.draw_spring(G,
                           with_labels=True,
                           labels=labels,
                           node_list=node_list,
                           node_size=node_size,
                           edge_color=edge_colour,
                           node_color=node_colour)
        elif graph_type == 'shell':
            nx.draw_shell(G,
                          with_labels=True,
                          labels=labels,
                          node_list=node_list,
                          node_size=node_size,
                          edge_color=edge_colour,
                          node_color=node_colour)
        # elif graph_type == 'protein':
        # self.draw_protein(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
        #                   edge_color=edge_colour, node_color=node_colour, back_bone, side_chains, terminators)
        else:
            nx.draw_networkx(G,
                             with_labels=True,
                             labels=labels,
                             node_list=node_list,
                             node_size=node_size,
                             edge_color=edge_colour,
                             node_color=node_colour)
        plt.show()
    print("total number of links:")
    print(total_num)
    print("number of rewired links:")
    print(rewired_num)
    return network

# =========================== MAIN CODE BELOW ==============================

if __name__ == "__main__":
    np.random.seed(42)
    #visualizing the rings for p = 0 ...
    graph1 = ws(15, 2, 0.1)
    fig1 = plt.figure()
    ax = fig1.add_subplot(111)
    nx.draw_circular(graph1)

    figure_filename = 'Small_world_ring.pdf'


    fig1.savefig(figure_filename)
    # or just use plt.show() and save manually

    total_num_edges = len(list(graph1.edges()))
    print("Total number of edges for n = 15, m = 2, p = 0 :")
    print(total_num_edges)
    #... and p = 0.5
    graph2 = ws(100, 2, 0.5)
    fig2 = plt.figure()
    ax = fig2.add_subplot(111)
    nx.draw_circular(graph2, node_size=20)