def observe():
    global initialConditions
    global g,estado,f
    estado=[]
    contadorAgregado=[]
    cla()
    node_labels={}
    cmapMio=creaCmap(5)
    for i in g.nodes_iter():
        node_labels[i]=g.node[i]['tipo']    
    nx.draw_networkx (g, k=0.8,node_color = [g.node[i]['tipo'] for i in g.nodes_iter()],
            pos = g.pos,cmap=cmapMio, labels=node_labels)
    for i in g.nodes_iter():
        estado.append(g.node[i]['tipo'])
    contador=collections.Counter(estado)
    contadorAgregado=[contador[0],contador[1],contador[2]+contador[3],contador[4]]
    print contadorAgregado
    wr.writerow(contadorAgregado)
    if initialConditions == 0:
        # Saving data if the simulation, using f defined in initialize()
        f.write('Tipo 1' + 'Tipo 2'+'Tipo 3'+'Patogeno' +"\n")
        f.write(str(contadorAgregado) +"\n")
        f.write('Matrix'+"\n")
        initialConditions=1       
        np.savetxt(f,betaMatrix, fmt='%.4e') 
        f.close()
示例#2
0
文件: graphmodel.py 项目: ihler/pyGM
  def drawFactorGraph(self,var_color='w',factor_color=(.2,.2,.8),**kwargs):
    """Draw a factorgraph using networkx function calls

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

    Example:
    >>> model.drawFactorGraph( var_labels={0:'0', ... } )    # keyword args passed to networkx.draw()
    """
    # TODO: specify var/factor shape,size, position, etc.; return G? silent mode?
    import networkx as nx
    G = nx.Graph()
    vNodes = [v.label for v in self.X if v.states > 1]   # list only non-trivial variables
    fNodes = [-i-1 for i in range(len(self.factors))]    # use negative IDs for factors
    G.add_nodes_from( vNodes )
    G.add_nodes_from( fNodes )
    for i,f in enumerate(self.factors):
      for v1 in f.vars:
        G.add_edge(v1.label,-i-1)
   
    pos = nx.spring_layout(G)   # so we can use same positions multiple times...
    kwargs['var_labels']  = kwargs.get('var_labels',{n:n for n in vNodes})
    kwargs['labels'] = kwargs.get('var_labels',{})
    nx.draw_networkx(G,pos, nodelist=vNodes,node_color=var_color,**kwargs)
    kwargs['labels'] = kwargs.get('factor_labels',{})    # TODO: need to transform?
    nx.draw_networkx_nodes(G,pos, nodelist=fNodes,node_color=factor_color,node_shape='s',**kwargs)
    nx.draw_networkx_edges(G,pos,**kwargs)
    return G
示例#3
0
def draw(g,vi_map=None,traffic_map=None,events=[],with_labels=False,save=False,filename="out.png"):
    pos = {node_id:(g.node[node_id]['data'].lon, g.node[node_id]['data'].lat) for node_id in g.nodes()}

    node_color = [(1,1,1) for i in g.nodes() ]
    if traffic_map!=None:
        for e in events:
            mesh_node = e.path[ e.pos ]
            if e.status == te.TrafficEvent.RUNNING:
                # print "PAINTING",e.id, e.pos, e.path[ e.pos ], g.nodes()[ e.path[ e.pos ] ]

                blue = math.floor(e.last_5_avg_speed)/2.0
                if blue>1:
                    blue = 1

                red=0
                if blue<1/20.0:
                    red = 1-10*blue

                node_color[ mesh_node ] = (red,0,blue)
            elif e.status == te.TrafficEvent.FINISHED:
                node_color[ mesh_node ] = (1,1,1)

    fig = plt.figure(frameon=False,dpi=90)
    ax = fig.add_axes( [0,0,2,2])
    ax.axis('off')
    nx.draw_networkx(g,pos=pos,arrows=False,node_size=18,with_labels=with_labels,linewidths=0.2,node_color=node_color,vmin=0,vmax=10)
    if save:
        plt.savefig(filename,dpi=70,bbox_inches='tight')       
    else:
        plt.show()
    plt.close(fig)  
示例#4
0
def initialize():

    G.add_node("A")
    G.add_node("B")
    G.add_node("C")
    G.add_node("D")
    G.add_node("E")
    G.add_node("F")

    labels = {k: k for k in G.nodes()}

    G.add_edge("A", "F", weight=1)
    G.add_edge("A", "E", weight=3)
    G.add_edge("A", "C", weight=4)
    G.add_edge("F", "B", weight=3)
    G.add_edge("F", "E", weight=2)
    G.add_edge("B", "D", weight=3)
    G.add_edge("B", "E", weight=2)
    G.add_edge("E", "D", weight=4)
    G.add_edge("E", "C", weight=2)
    G.add_edge("C", "D", weight=1)

    labels = nx.get_edge_attributes(G, "weight")
    plt.title("Single-Router Network")
    nx.draw(G, pos=nx.spectral_layout(G))
    nx.draw_networkx(G, with_labels=True, pos=nx.spectral_layout(G))
    nx.draw_networkx_edge_labels(G, pos=nx.spectral_layout(G), edge_labels=labels)
    plt.show()
示例#5
0
def draw(inF):
    G = nx.Graph()

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

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

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

    inFile = open(inF)
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        for i in range(len(fields)-1):
            G.add_edge(fields[i], fields[i+1])
    inFile.close()
    nx.draw_networkx(G,pos=nx.spring_layout(G), node_size=800, font_size=6, node_color=LC)
    limits=plt.axis('off')
    plt.savefig(inF + '.pdf')
示例#6
0
	def draw(self):
		positions = {}
		Tree.get_positions(self, positions, x=(0, 10), y=(0, 10))
		g = self.to_graph()
		plt.axis('on')
		nx.draw_networkx(g, positions, node_size=1500, font_size=24, node_color='g')
		plt.show()
示例#7
0
def reactionCenter(filename):
	# in this method, g2 do not need to be subgraph of g1
	mcs = fmcsWithPath(filename=filename)
	# print(mcs['content1'])
	# print(mcs['content2'])
	# print(mcs['contentmcs'])

	# g1 = input_chem_content(mcs['content1'], 'g1')
	g1 = graphFromSDF(StringIO(mcs['content1']))[0]
	print g1.node
	# nx.draw_networkx(g1)
	# pyplot.show( )

	# g2 = input_chem_content( mcs['content2'], 'g2' )
	g2 = graphFromSDF( StringIO( mcs['content2'] ) )[0]
	print g2.node
	# nx.draw_networkx( g2)
	# pyplot.show( )

	# gmcs = input_chem_content(mcs['contentmcs'], 'g2')
	gmcs = graphFromSDF( StringIO( mcs['contentmcs'] ) )[0]
	nx.draw_networkx(gmcs)
	pyplot.show()

	print getReactionCenter(g1, gmcs)
示例#8
0
 def showbgraph(event):
     ax.clear()
     setp(ax, xticks=[], yticks=[])
     layout = radio_layout.layout
     NX.draw_networkx(G, layout, alpha=0.1, labels={})
     NX.draw_networkx(BG, layout, node_color='y')
     draw()
示例#9
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()
def make_tree_figure(wanted_seqs, trop_dict, tree_file):
    mat_data = get_pairwise_distances(wanted_seqs, tree_file = tree_file)
    tree = Phylo.read(open(tree_file), 'newick')
    net = Phylo.to_networkx(tree)
    
    node_mapping = {}
    clade = 1
    for node in net.nodes():
        if node.name is None:
            node_mapping[node] = 'Clade-%i' % clade
            clade += 1
        else:
            node_mapping[node] = node.name
    new_net = networkx.relabel_nodes(net, node_mapping)
    
    colors = []
    for node in new_net.nodes():
        if node.startswith('Clade'):
            colors.append('w')
        elif trop_dict[node]:
            colors.append('g')
        elif not trop_dict[node]:
            colors.append('r')
        else:
            print node
    #print colors, len(colors), len(new_net.nodes())
    pos = networkx.graphviz_layout(new_net, 'twopi')
    
    networkx.draw_networkx(new_net, pos, with_labels = False, node_color = colors)
def graph_show(graph, font_size=12):
    pylab.rcParams['figure.figsize'] = (16.0, 12.0)
    try:
        nx.draw_networkx(graph,pos=nx.spring_layout(graph), node_size=6, alpha=0.1, font_size=font_size)
    except:
        print 'umm'
    pylab.rcParams['figure.figsize'] = (10.0, 4.0)
示例#12
0
文件: run.py 项目: LubuntuFu/minicps
def laucher(graph, mininet_config, draw_mpl=False, write_gexf=False):
    """
    Launch the miniCPS SWaT simulation

    :graph: networkx graph
    :mininet_config: function pointer to the mininet configuration
    :draw_mpl: flag to draw and save the graph using matplotlib
    """

    # TODO: use different color for plcs, switch and attacker
    if draw_mpl:
        nx.draw_networkx(graph)
        plt.axis('off')
        # plt.show()
        plt.savefig("examples/swat/%s.pdf" % graph.name)

    if write_gexf:
        g_gexf = nx.write_gexf(graph, "examples/swat/l1_gexf.xml")
        # g2 = nx.read_gexf("examples/swat/g_gexf.xml")

    # Build miniCPS topo
    topo = TopoFromNxGraph(graph)
    controller = POXSwat
    net = Mininet(
        topo=topo,
        controller=controller,
        link=TCLink,
        listenPort=6634)

    mininet_config(net)
def observe():
    global initialConditions
    global g,estado,f,numNodos,numTipoNodos
    estado=[]
    contadorAgregado=[]
    cla()
    node_labels={}
    cmapMio=creaCmap(4)
    for i in g.nodes_iter():
        node_labels[i]=g.node[i]['tipo']    
    nx.draw_networkx (g, k=0.8,node_color = [g.node[i]['tipo'] for i in g.nodes_iter()],
            pos = g.pos,cmap=cmapMio, labels=node_labels)
    for i in g.nodes_iter():
        estado.append(g.node[i]['tipo'])
    contador=collections.Counter(estado)
    contadorAgregado=contador.values()
    wr.writerow(contadorAgregado)
    print contadorAgregado
    if initialConditions == 0:
        # Saving data used in simulation, using f of file defined in initialize()
        f.write('GRID de ')
        f.write(str(numNodos)+"\n y tipos de nodos: ")
        f.write(str(numTipoNodos)+"\n")
        f.write(str(contadorAgregado) +"\n")
        f.write('Matrix'+"\n")
        initialConditions=1       
        np.savetxt(f,betaMatrix, fmt='%.4e') 
        f.close()
	def plot(self,figure):		
		changed	= False
		for ip in self.stats:
			if ip is not "127.0.0.1" and not self.graph.has_node(ip):
				self.graph.add_node(ip,node_size=4000,node_shape="s")
				self.graph.add_edge(ip,"127.0.0.1",attr_dict={"label":"N/A"})
				changed = True
			for port in self.stats[ip]:
				#pnode = ip + ":" + port
				pnode = port
				if not self.graph.has_node(pnode):
					statName = ip + ":" + port
					self.graph.add_node(pnode,attr_dict={"node_size":700,"node_shape":"o","font_size":8})
					self.graph.add_edge(pnode ,ip, attr_dict={"label":"N/A"})
					changed = True
		if changed:
			figure.clf()
			pos = nx.spring_layout(self.graph, weight=None, iterations=100, scale = 2)
			#draw ip nodes
			ipNodeList = list(self.stats)
			#print(ipNodeList)
			try:
				nx.draw_networkx(self.graph, 
							nodelist = ipNodeList, 
							pos = pos, 
							with_labels = True,
							node_size = 4000 , 
							node_shape = "p", 
							font_size = 8
						)
			except nx.exception.NetworkXError:	# catch some error about a node not having a position yet (we just re-render, that does it)
				pass
			#draw port nodes
			portList = list(self.stats.values())
			portNodesList = [ item for sublist in (list(e) for e in portList) for item in sublist ]
			try:
				nx.draw_networkx_nodes(self.graph, 
							nodelist = portNodesList, 
							pos = pos ,
							with_labels = True,
							node_size = 700 , 
							node_shape = "o", 
							font_size=8
						)
				edges = self.graph.edges(data=True)
				labels = {}
				for (a, b, *c) in edges:
					stats = "N/A"
					if a in self.stats:
						if b in self.stats[a]:
							labels[a,b] = self.stats[a][b]
					else:
						if a in self.stats[b]:
							labels[b,a] = self.stats[b][a]
				nx.draw_networkx_edge_labels(self.graph, pos = pos, edge_labels=labels,ax=None)
			except nx.exception.NetworkXError:	# catch some error about a node not having a position yet (we just re-render, that does it)
				pass
			# draw connStats
			statNodesList = list(self.statNodes)
			figure.canvas.draw()
示例#15
0
    def create_simple_graph(self,name):
        import networkx as nx
        G=nx.Graph()
        for i,r in enumerate(self.reslist):
            G.add_node(i+1,name=r.name)
        print G.nodes()

        
        h = self.hbond_matrix()
        nr = numpy.size(h,0)
        for i in range(nr):
            for j in range(i+1,nr):
                if GenericResidue.touching(self.reslist[i], self.reslist[j],2.8):
                    print 'adding edge',i+1,j+1
                    G.add_edge(i+1,j+1,name="special")                     
 
#        pos0=nx.spectral_layout(G)
#        pos=nx.spring_layout(G,iterations=500,pos=pos0)

#        pos=nx.spring_layout(G,iterations=500)
        
#        nx.draw_shell(G)

        pos0=nx.spectral_layout(G)
        pos=nx.spring_layout(G,iterations=500,pos=pos0)
#        pos=nx.graphviz_layout(G,root=1,prog='dot')
#        nx.draw(G)
        nx.draw_networkx(G,pos)
                     
        plt.axis('off')
        plt.savefig(name)       
示例#16
0
def calc_clustering_coefficient(g, dest_file):
    """
    calc_clustering_coefficient(g)
    Calculate & plot clustering coefficient of the graph g and writes data to the created data output file
    :param g:   graph as source
    :return:    ---
    """
    func_intro = "\n\nClustering Co-Efficient ..."
    logging.info(cs_ref, func_intro)
    print func_intro
    with open(dest_file, "a") as dat_file:
        dat_file.write(func_intro)

    cce = nx.clustering(g)  # calculate clustering co-efficient
    with open(dest_file, "a") as dat_file:
        dat_file.write("\n\tClustering Coefficients for nodes in graph = \t" + str(cce))
    average_cce = nx.average_clustering(g)
    with open(dest_file, "a") as dat_file:
        dat_file.write("\n\tAverage Clustering Coefficient for graph = \t" + str(average_cce))

    for edge in g.edges():  # plot clustering co-efficient
        if floor(edge[0] / 5.) != floor(edge[1] / 5.):
            if random.random() < 0.95:
                g.remove_edge(edge[0], edge[1])
    plt.figure(3)
    fixed_pos = {1: (0, 0), 10: (1, 1), 30: (1, 0), 50: (0, 1)}
    pos = nx.spring_layout(g, fixed=fixed_pos.keys(), pos=fixed_pos)
    nx.draw_networkx(g, pos=pos)
    plt.title("Clustering Co-efficient" + src_file)
    plt.savefig("plots/cs1_clustering_coefficient.png")
    plt.show()
示例#17
0
    def drawgraph(self,path,nodelist):
        color = {}
        graph = nx.Graph()
        for item in nodelist:
            graph.add_node(item.key.decode('utf-8'))
            if item.key in path.split('->'):
                color[item.key.decode('utf-8')] = 'green'

        for item in nodelist:
            if item.path == '':
                continue
            s = item.path.split('->')
            for i in range(0,len(s) - 1):
                if i == 0:
                    continue
                graph.add_edge(s[i].decode('utf-8'),s[i+1].decode('utf-8'))
        values = [color.get(node,'red') for node in graph.nodes() ]
        pos = nx.spring_layout(graph)
        if len(nodelist) > 500:
            nx.draw_networkx(graph,font_family='SimHei', node_size=50,node_color=values, font_size = 5)
        else:
            nx.draw_networkx(graph,font_family='SimHei', node_size=1000,node_color=values, font_size = 10)
        plt.savefig('HSearch.png')
        plt.close()
        return None
def strongly_connected_components():
    conn = sqlite3.connect("zhihu.db")     
    #following_data = pd.read_sql('select user_url, followee_url from Following where followee_url in (select user_url from User where agree_num > 50000) and user_url in (select user_url from User where agree_num > 50000)', conn)        
    following_data = pd.read_sql('select user_url, followee_url from Following where followee_url in (select user_url from User where agree_num > 10000) and user_url in (select user_url from User where agree_num > 10000)', conn)        
    conn.close()
    
    G = nx.DiGraph()
    cnt = 0
    for d in following_data.iterrows():
        G.add_edge(d[1][0],d[1][1])
        cnt += 1
    print 'links number:', cnt

    scompgraphs = nx.strongly_connected_component_subgraphs(G)
    scomponents = sorted(nx.strongly_connected_components(G), key=len, reverse=True)
    print 'components nodes distribution:', [len(c) for c in scomponents]
    
    #plot graph of component, calculate saverage_shortest_path_length of components who has over 1 nodes
    index = 0
    print 'average_shortest_path_length of components who has over 1 nodes:'
    for tempg in scompgraphs:
        index += 1
        if len(tempg.nodes()) != 1:
            print nx.average_shortest_path_length(tempg)
            print 'diameter', nx.diameter(tempg)
            print 'radius', nx.radius(tempg)
        pylab.figure(index)
        nx.draw_networkx(tempg)
        pylab.show()

    # Components-as-nodes Graph
    cG = nx.condensation(G)
    pylab.figure('Components-as-nodes Graph')
    nx.draw_networkx(cG)
    pylab.show()    
示例#19
0
    def print_graph(self, special_nodes):
        G = nx.Graph()
        self.get_graph(self.root, G)
        poss = hierarchy_pos(G, self.root.val[1])
        nx.draw_networkx(G, pos=poss, default=True, node_color='y')

        plt.show()
示例#20
0
文件: lfm.py 项目: rkdarst/pcd
    def savefig(col):
        global idx
        pylab.clf()
        #from pcd.support.matplotlibutil import get_axes, save_axes
        #ax, extra = get_axes('/home/darstr1/proj/tmp-img/%05d.png'%0)
        #print ax
        nx.draw_networkx(g, pos=pos,
                         node_list=g.nodes(),
                         node_color=[col[n] for n in g.nodes()],
                         with_labels=False)
        #save_axes(ax, extra)

        fig = pylab.gcf()
        ax = pylab.gca()
        dpi = fig.dpi
        bbox = ax.collections[0].get_window_extent(fig)
        from matplotlib.transforms import TransformedBbox, Affine2D
        bbox2 = TransformedBbox(bbox, Affine2D().scale(1. / dpi))
        bbox._points[0] -= .15 * dpi
        bbox._points[1] += .15 * dpi

        ax = pylab.gca()
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)
        pylab.savefig('/home/darstr1/proj/tmp-imgs/%05d.png'%idx,
                      bbox_inches=bbox2)
        idx += 1
def pagerank_hits():
    conn = sqlite3.connect("zhihu.db")     
    #following_data = pd.read_sql('select user_url, followee_url from Following where followee_url in (select user_url from User where agree_num > 50000) and user_url in (select user_url from User where agree_num > 50000)', conn)        
    following_data = pd.read_sql('select user_url, followee_url from Following where followee_url in (select user_url from User where agree_num > 10000) and user_url in (select user_url from User where agree_num > 10000)', conn)        
    conn.close()
    
    G = nx.DiGraph()
    cnt = 0
    for d in following_data.iterrows():
        G.add_edge(d[1][0],d[1][1])
        cnt += 1
    print 'links number:', cnt
    pylab.figure(0)
    nx.draw_networkx(G)
    pylab.show()

    # PageRank
    pr = nx.pagerank(G)
    prsorted = sorted(pr.items(), key=lambda x: x[1], reverse=True)
    print 'pagerank top 100:\n'
    for p in prsorted[:100]:
        print p[0], p[1]
    
    # HITS
    hub, auth = nx.hits(G)
    print 'hub top 100:\n'
    for h in sorted(hub.items(), key=lambda x: x[1], reverse=True)[:100]:
        print h[0], h[1]
    print '\nauth top 100:\n'    
    for a in sorted(auth.items(), key=lambda x: x[1], reverse=True)[:100]:     
        print a[0], a[1]
示例#22
0
def main():

    G_igraph, G_nx, nodes_vector = generate_data()

    aca0, aca1 = separate_data_by_academy(nodes_vector, G_nx)

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

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

    plt.axis('off')

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

    plt.axis('off')
    plt.show()
示例#23
0
def draw_graph(graph):

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

    # create networkx graph
    G=nx.Graph()
    #G=nx.cubical_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
    #pos = nx.shell_layout(G)
    #pos = nx.spectral_layout(G)
    pos = nx.random_layout(G) # Funciona melhor
    #pos = nx.circular_layout(G) # Mais ou menos
    #pos = nx.fruchterman_reingold_layout(G) # Funciona melhor

    #nx.draw(G, pos)
    nx.draw_networkx(G)

    # show graph
    plt.axis('off')
    plt.show()
示例#24
0
 def draw(self):
     """
     Draw a network graph of the employee relationship.
     """
     if self.graph is not None:
         nx.draw_networkx(self.graph)
         plt.show()
def tree_width(nxg,i):
	maxsize=1000000000
	junction_tree=nx.Graph()
	max_junction_tree_node=junction_tree
	all_subgraphs=create_all_subgraphs(nxg.edges(),i)
	print "All subgraphs:",all_subgraphs
	print "============================================"
	for k0 in all_subgraphs:
		for k1 in all_subgraphs:
			hash_graph_k0 = hash_graph(k0)
			hash_graph_k1 = hash_graph(k1)
			if (hash_graph_k0 != hash_graph_k1) and len(set(k0).intersection(set(k1))) > 0:
				junction_tree.add_edge(hash_graph_k0,hash_graph_k1)
				if len(k0) < maxsize:
					max_junction_tree_node=k0
					maxsize = len(k0)
				if len(k1) < maxsize:
					max_junction_tree_node=k1
					maxsize = len(k1)
	print "============================================"
	print "Junction Tree (with subgraphs of size less than",i,") :"
	nx.draw_networkx(junction_tree)
	plt.show()
	print "============================================"
	print "Junction Tree Width for subgraphs of size less than ",i," - size of largest node set:",maxsize
示例#26
0
def plot_osm_network(G,node_size=10,with_labels=False,ax=None):
    plt.figure()
    pos = {}
    for n in G.nodes():
        pos[n] = (G.node[n].lon, G.node[n].lat)
    nx.draw_networkx(G,pos,node_size=node_size,with_labels=with_labels,ax=ax)
    plt.show()
示例#27
0
def create_networkx(node_list, edge_list, args):
    graph = nx.Graph()
    print 'Initializing'
    size_list = []
    clean_node_list = []
    for item in node_list:
        nodesize = 300
        for edge in edge_list:
            if item == edge[1]:
                nodesize += 100
        size_list.append(nodesize)
        clean_node_list.append(os.path.basename(item))
    graph.add_nodes_from(clean_node_list)
    print 'Nodes set'
    for item in edge_list:
        from_node = os.path.basename(item[1])
        to_node = os.path.basename(item[0])
        graph.add_edge(from_node, to_node)
    print 'Edges set'
    print 'Creating Graph'
    position = nx.spring_layout(graph)
    for item in position:
        position[item] *= 10
    nx.draw_networkx(graph,
                     pos=position,
                     font_size=10,
                     node_size=size_list)
    print 'Drawing Graph'
    plt.show()
    print 'DONE'
def draw_basic_network(G,src_list):
  slpos = nx.spring_layout(G) # see this for a great grid layout [1]
  nx.draw_networkx(G, pos=slpos, node_color='b', nodelist=src_list, with_labels=False,node_size=20, \
                   edge_color='#7146CC')
  nx.draw_networkx_nodes(G, pos=slpos, node_color='r', nodelist=[x for x in G.nodes() if x not in src_list], \
                         alpha=0.8, with_labels=False,node_size=20)
  plt.savefig('figures/basicfig', bbox_inches='tight', pad_inches=0)
示例#29
0
def draw_geograph(g, node_color='r', edge_color='b', node_label_field=None,
                  edge_label_field=None, node_size=200, node_label_x_offset=0, 
                  node_label_y_offset=0, node_label_font_size=12, 
                  node_label_font_color='k'):
    """
    Simple function to draw a geograph via matplotlib/networkx
    Uses geograph coords (projects if needed) as node positions
    """

    # transform to projected if not done so
    flat_coords = g.transform_coords(gm.PROJ4_FLAT_EARTH)

    node_pos = {nd: flat_coords[nd] for nd in g.nodes()}
    label_pos = {nd: [flat_coords[nd][0] + node_label_x_offset, 
                      flat_coords[nd][1] + node_label_y_offset] 
                      for nd in g.nodes()}

    # Draw nodes
    nx.draw_networkx(g, pos=node_pos, node_color=node_color,
        with_labels=False, edge_color=edge_color, node_size=node_size)

    if node_label_field:
        if node_label_field != 'ix':
            label_vals = nx.get_node_attributes(g, node_label_field)
            nx.draw_networkx_labels(g, label_pos, labels=label_vals, 
                font_size=node_label_font_size, font_color=node_label_font_color)

        else: # label via ids
            nx.draw_networkx_labels(g, label_pos, labels=g.nodes(), 
                font_size=node_label_font_size, font_color=node_label_font_color)

    # handle edge labels if needed
    if edge_label_field:
        edge_labels = nx.get_edge_attributes(g, edge_label_field)
        nx.draw_networkx_edge_labels(g, pos=node_pos, edge_labels=edge_labels)
示例#30
0
 def doGraph(self,G,labels):
     pos = Plotter.hierarchical_layout(G)
     xs = map(lambda x:pos[x][0],pos)
     ys = map(lambda x:pos[x][0],pos)
     P.axis([min(xs)-0.1,
             max(xs)+0.1,
             min(ys)-0.1,
             max(ys)+0.1])
     P.subplots_adjust(left=0,
                       right=1,
                       bottom=0,
                       top=0.9)
         
     NX.draw_networkx(G, pos, font_size=8, labels=labels, edge_color='g')
     if labels:
         for (a,b,c) in G.edges():
             # the shorter line, the closer to lower node
             ax,ay=pos[a]
             bx,by=pos[b]
             l = ((ax-bx)**2+(ay-by)**2)**0.5
             ra = 1/(l+1)
             rb = l/(l+1)
             x=(ra*ax+rb*bx)
             y=(ra*ay+rb*by)
             P.text(x,y,c.type,
                    size=8,
                    horizontalalignment='center',
                    verticalalignment='center',
                    multialignment='left')
示例#31
0
refill = 200
v_low = 30
v_high = 50

times = 1000

random_n_list = list(itertools.product(range(0, g_side), range(0, g_side)))
locations_set = random.sample(random_n_list, locations_count + 1)
g_los = locations_set

po = g_los[0]

G = nx.grid_2d_graph(g_side, g_side)
pos = dict((n, n) for n in G.nodes())
labels = dict(((i, j), i * 0 + j * 0) for i, j in G.nodes())
nx.draw_networkx(G, pos=pos, labels=labels, node_color="r", node_size=0)

list2 = []
for index in range(0, len(g_los)):
    list2.append(index)

posiList = dict(zip(list2, g_los))
#print(posiList)

g_overload_set = [
    random.randint(v_low, v_high) for _ in range(locations_count)
]
location_overload_set = dict(zip(g_los[1:], g_overload_set))

nx.draw_networkx_nodes(G,
                       posiList,
示例#32
0
def draw(g):
    pos = nx.shell_layout(g)
    nx.draw_networkx(g, pos)
ax.axis('equal')

pieBigramWords, _, _ = ax.pie(list(df_bigramMostCommon20['frequency']),
                              radius=1.3,
                              labels=list(
                                  df_bigramMostCommon20['bigramWords']),
                              autopct='%1.2f%%')
plt.setp(pieBigramWords, width=0.3, edgecolor='white')
plt.show()

#graph of bigram words from tweets
graphOfWords = nx.Graph()

for k, v in df_bigramMostCommon20Dict[0].items():
    print(k[0], '-->', k[1])
    graphOfWords.add_edge(k[0], k[1], weight=(v * 10))

graphOfWords.add_node("Airline", weight=100)

fig, ax = plt.subplots(figsize=(10, 10))
position = nx.spring_layout(graphOfWords, k=1)
nx.draw_networkx(graphOfWords, position, ax=ax, with_labels=False)
for key, value in position.items():
    x, y = value[0] + 0.025, value[1] + 0.05
    ax.text(x,
            y,
            s=key,
            bbox=dict(facecolor='yellow', alpha=0.25),
            horizontalalignment='center',
            fontsize=12)
plt.show()
示例#34
0
                                          p_quit=lmbda,
                                          n_iteration=20,
                                          remove_totters=False,
                                          n_jobs=multiprocessing.cpu_count(),
                                          verbose=False)
                dnew = knew[0][
                    0, 0] - 2 * (alpha * knew[0][0, 1] +
                                 (1 - alpha) * knew[0][0, 2]) + (
                                     alpha * alpha * k_list[idx1] + alpha *
                                     (1 - alpha) * k_g2_list[idx1] +
                                     (1 - alpha) * alpha * k_g1_list[idx2] +
                                     (1 - alpha) * (1 - alpha) * k_list[idx2])
                if dnew <= dhat:  # the new distance is smaller
                    print('I am smaller!')
                    dhat = dnew
                    gnew = gtemp.copy()
                    found = True  # found better graph.
                    r = 0
        if found:
            gihat_list = [gnew]
            dis_gs.append(dhat)
        else:
            r += 1
    dis_best.append(dhat)
    g_best += ([g0hat] if len(gihat_list) == 0 else gihat_list)

for idx, item in enumerate(alpha_range):
    print('when alpha is', item, 'the shortest distance is', dis_best[idx])
    print('the corresponding pre-image is')
    nx.draw_networkx(g_best[idx])
    plt.show()
    def plot(self,
             path=None,
             fig=None,
             plotTitle=None,
             baseSize=400,
             node_size=10,
             showLabels=True,
             showEdgeWeights=True,
             showAxes=True):

        if not fig:
            fig = plt.figure()

        # scale node sizes by string length only if all node labels are strings
        allStrs = bool(self.nodes()) and all(
            isinstance(elem, str) for elem in self.nodes())
        pos = nx.get_node_attributes(self, 'pos')
        if allStrs:
            node_size = [len(v) * baseSize for v in self.nodes()]
            nx.draw_networkx(self,
                             pos=pos,
                             with_labels=showLabels,
                             node_size=node_size)
        else:
            nx.draw_networkx(self,
                             pos=pos,
                             with_labels=showLabels,
                             node_size=node_size,
                             cmap=plt.get_cmap('jet'))

        # show edge weights as well
        if showEdgeWeights:
            labels = nx.get_edge_attributes(self, 'weight')
            nx.draw_networkx_edge_labels(self, pos, edge_labels=labels)

        # draw path through the graph if it exists
        if path:

            nx.draw_networkx_nodes(self,
                                   pos,
                                   nodelist=path,
                                   node_color='r',
                                   node_size=node_size)

            path_edges = self.getPathEdges(path)
            nx.draw_networkx_edges(self,
                                   pos,
                                   edgelist=path_edges,
                                   edge_color='r',
                                   width=4)

        # Axes settings
        ax = plt.gca()
        ax.set_title(plotTitle)
        if showAxes:
            ax.tick_params(left=True,
                           bottom=True,
                           labelleft=True,
                           labelbottom=True)
        else:
            [sp.set_visible(False) for sp in ax.spines.values()]
            ax.set_xticks([])
            ax.set_yticks([])

        return (fig, ax)
    def plot_centroids(
        self,
        adata,
        use_rep,
        obs_col="leiden",
        ctr_size=300,
        pt_size=75,
        draw_edges=True,
        highlight_edges=False,
        save_to=None,
    ):
        """
        General plotting function for cluster centroid graph and MST 
        (i.e. from "leiden" or "louvain") and cute arrows and labels

        Parameters
        ----------

        adata : anndata.AnnData
            object to pull dimensionality reduction from
        use_rep : str
            `adata.obsm` key to plot from (i.e. "X_pca")
        obs_col : str, optional (default="leiden")
            name of column in `adata.obs` to use as cell IDs (i.e. "leiden")
        ctr_size : float, optional (default=300)
            size of centroid points in plot
        pt_size : float, optional (default=75)
            size of points in plot
        draw_edges : bool, optional (default=True)
            draw edges of minimum spanning tree between all centroids
        highlight_edges : list of int, optional (default=False)
            list of edge IDs as tuples to highlight in red on plot. e.g. 
            `set(adata.uns['X_tsne_centroid_MST'].edges).difference(set(adata.uns['X_umap_centroid_MST'].edges))`
            with output {(0,3), (0,7)} says that edges from centroid 0 to 3 and 0 to 7 
            are found in 'X_tsne_centroids' but not in 'X_umap_centroids'. highlight 
            the edges to show this.
        save_to : str, optional (default=None)
            path to `.png` file to save output. do not save if None

        Returns
        -------

        `self.fig`, `self.ax` edited; plot saved to `.png` file if `save_to` is not 
        None
        """
        clu_names = adata.obs[obs_col].unique().astype(str)
        # use existing scanpy colors, if applicable
        if obs_col == "leiden" and "leiden_colors" in adata.uns.keys():
            colors = [
                adata.uns["leiden_colors"][x]
                for x in adata.obs.leiden.unique().astype(int)
            ]
        elif obs_col == "louvain" and "louvain_colors" in adata.uns.keys():
            colors = [
                adata.uns["louvain_colors"][x]
                for x in adata.obs.louvain.unique().astype(int)
            ]
        # otherwise, get new color mapping from obs_col using self.cmap
        else:
            colors = self.cmap(np.linspace(0, 1, len(clu_names)))

        # draw points in embedding first
        sns.scatterplot(
            x=adata.obsm[use_rep][:, 0],
            y=adata.obsm[use_rep][:, 1],
            ax=self.ax,
            s=pt_size,
            alpha=0.1,
            color="gray",
            legend=False,
            edgecolor="none",
        )

        # draw MST edges if desired, otherwise just draw centroids
        if not draw_edges:
            self.ax.scatter(
                x=adata.uns["{}_centroids".format(use_rep)][:, 0],
                y=adata.uns["{}_centroids".format(use_rep)][:, 1],
                s=ctr_size,
                c=colors,
                edgecolor="none",
            )
        else:
            pos = dict(
                zip(clu_names,
                    adata.uns["{}_centroids".format(use_rep)][:, :2]))
            nx.draw_networkx(
                adata.uns["{}_centroid_MST".format(use_rep)],
                pos=pos,
                ax=self.ax,
                with_labels=False,
                width=2,
                node_size=ctr_size,
                node_color=colors,
            )
            # highlight edges if desired
            if highlight_edges:
                nx.draw_networkx_edges(
                    adata.uns["{}_centroid_MST".format(use_rep)],
                    pos=pos,
                    ax=self.ax,
                    edgelist=highlight_edges,
                    width=5,
                    edge_color="red",
                )

        if save_to is None:
            return
        else:
            plt.savefig(fname=save_to,
                        transparent=True,
                        bbox_inches="tight",
                        dpi=1000)
示例#37
0
dev_ourense = qml.device("qiskit.ibmq", wires=5, backend="ibmq_ourense")

##############################################################################
#
# First, we can take a look at the arrangement of the qubits on the processor
# by plotting its hardware graph.

import matplotlib.pyplot as plt
import networkx as nx

ourense_hardware_graph = nx.Graph(
    dev_ourense.backend.configuration().coupling_map)

nx.draw_networkx(
    ourense_hardware_graph,
    node_color="cyan",
    labels={x: x
            for x in range(dev_ourense.num_wires)},
)

##############################################################################
#
# .. figure:: ../demonstrations/quantum_volume/ourense.svg
#     :align: center
#     :width: 75%
#

##############################################################################
#
# This hardware graph is not fully connected, so the quantum compiler will have
# to make some adjustments when non-connected qubits need to interact.
#
示例#38
0
######################## FUNÇÃO PRINCIPAL ###########################
arquivo = open('grafo2', 'r')
nvertices = int(arquivo.readline())
vertices = tuple(arquivo.readline().split())
narestas = int(arquivo.readline())
lista_arestas = []
for i in range(narestas):
    lista_arestas.append(arquivo.readline().strip().replace(' ', ''))
grafo = nx.Graph()

grafo.add_nodes_from(vertices)
grafo.add_edges_from(lista_arestas)

profundidade = busca_profundidade(grafo)
print("--> Algoritmo DFS")
imprimir(profundidade)
print()
print()
print('=================================================')
print()
print("--> Algoritmo BFS")
largura = (busca_largura(grafo))
imprimir(largura)

nx.draw_networkx(grafo,
                 with_labels=True,
                 pos=nx.planar_layout(grafo),
                 node_color='r',
                 edge_color='b')
plt.show()
示例#39
0
def visualizarGrafo(arr):
    G = nx.Graph()
    G.add_edges_from(arr)
    nx.draw_networkx(G)
    plt.show()
示例#40
0
def draw_graph(G):
    '''
    Draws networkx graph G
    '''
    nx.draw_networkx(G)
    plt.show()
    return heuristics


heuristics = getHeuristics(G)
node_pos = nx.get_node_attributes(G, 'pos')

#call BFS to return set of all possible routes to the goal
route_bfs = GBfsTraverser()
routes = route_bfs.GBFS(G, heuristics, "SportsComplex", "ParkingLot")

route_list = route_bfs.path
#color the nodes in the route_bfs
node_col = [
    'darkturquoise' if not node in route_list else 'peru'
    for node in G.nodes()
]
peru_colored_edges = list(zip(route_list, route_list[1:]))
#color the edges as well
#print(peru_colored_edges)
edge_col = [
    'darkturquoise' if not edge in peru_colored_edges else 'peru'
    for edge in G.edges()
]
arc_label = nx.get_edge_attributes(G, 'label')
nx.draw_networkx(G, node_pos, node_color=node_col, node_size=450)
nx.draw_networkx_edges(G, node_pos, width=5, edge_color=edge_col)
#nx.draw_networkx_edge_labels(G, node_pos,edge_color= edge_col, edge_labels=arc_weight)

nx.draw_networkx_edge_labels(G, node_pos, edge_labels=arc_label)
plt.axis('off')
plt.show()
示例#42
0
        [0, 1, 1, 0],
        [0, 1, 1, 1],
        [0, 1, 1, 0],
        [1, 0, 1, 1],
        [1, 0, 0, 0],
    ]

    distribution = Distribution(samples)

    distribution._generate_bayes_net()

    for node_ind in distribution.bayes_net.nodes():
        print(distribution.bayes_net.node[node_ind])

    pos = nx.spring_layout(distribution.spanning_graph)

    edge_labels = dict([((
        u,
        v,
    ), d['weight']) for u, v, d in distribution.spanning_graph.edges(data=True)
                        ])

    nx.draw_networkx(distribution.spanning_graph, pos)
    nx.draw_networkx_edge_labels(
        distribution.spanning_graph,
        pos,
        edge_labels=edge_labels,
    )

    plt.show()
        del nodes[k]
    k += 1

##

pos = nx.spring_layout(H, iterations = 1000)
nx.draw_networkx_nodes(H, pos, nodelist = ['U19886'], node_color = 'r', node_size = 20)
nx.draw_networkx_nodes(H, pos, nodelist = nodes, node_color = 'b', node_size = 20)
nx.draw_networkx_nodes(H, pos, nodelist = google_employees, node_color = 'g', node_size = 20)
nx.draw_networkx_edges(H, pos)
plt.axis('off')
plt.show()

# On voit que le no U7091 est un fdp

##

nx.draw_networkx(H, pos, node_size = 20, font_size = 9)
plt.show()

##

nodes1 = list(G.nodes)

k=0
while k < len(nodes1):
    if nodes1[k] == 'U7091':
        del nodes1[k]
    k += 1
    
P = G.subgraph(nodes1)
示例#44
0
Q, offset = model.to_qubo()
bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=offset)

# Need to relabel variables for the first figure
bqm2 = bqm.relabel_variables({curr: v
                              for v, curr in enumerate(bqm.variables)},
                             inplace=False)

# Do the embedding
dwave_sampler = DWaveSampler()
A = dwave_sampler.edgelist
embedding = find_embedding(Q, A)

# Draw the QUBO as a networkx graph
G = bqm2.to_networkx_graph()
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos, font_size=10, node_size=150)
plt.show()

# Draw the embedded graph
G = dnx.chimera_graph(16, 16, 4)
dnx.draw_chimera_embedding(G,
                           embedding,
                           embedded_graph=bqm.to_networkx_graph(),
                           unused_color=None)
plt.show()

clique_embedding = find_clique_embedding(N, 16, 16, 4, A)
dnx.draw_chimera_embedding(G, clique_embedding, unused_color=None)
plt.show()
示例#45
0
def plot_paths(paths_data,
               G,
               mode=None,
               save_graph=False,
               show_graph=True,
               layout_seed=None,
               draw_edge_weights=False):
  """Plots the graph and all the generated paths (up to 8) in spring_layout."""
  utils.verify_paths(paths_data)
  if mode is None:
    mode = {}
  if save_graph:
    figsize = (10 * 1.8, 10)
    dpi = 200
    title_fontsize = 22
    legend_fontsize = 20
  else:
    figsize = (8 * 1.8, 8)
    dpi = 100
    title_fontsize = 18
    legend_fontsize = 16

  # path_nodes_pos = [
  #     (1, -1),
  #     (0.7, -0.1),
  #     (0.35, -0.5),
  #     (0.15, 0),
  #     (-0.1, -0.1),
  #     (-0.4, 0.3),
  #     (-0.6, -0.1),
  #     (-1, 1.1)
  # ]
  # path_nodes_pos = {paths_data[0][0][i]: path_nodes_pos[i] for i in range(8)}

  fig = plt.figure(figsize=figsize, dpi=dpi)
  # , k=1 / sqrt(G.number_of_nodes())  # the default spring coefficient
  pos = nx.spring_layout(
      G,
      seed=layout_seed,
      # pos=path_nodes_pos,
      k=5 / sqrt(G.number_of_nodes()),
      # fixed=path_nodes_pos.keys()
  )

  # Layouts
  # -------
  # circular_layout
  # spring_layout                <--
  # fruchterman_reingold_layout  <--
  # spiral_layout                <--

  # 1. Draw the graph
  node_size, path_node_size, failed_node_size = _node_sizes(G)
  nx.draw_networkx(G, pos, node_size=node_size, width=0.3, alpha=0.3,
                   with_labels=False, arrows=False)
  if draw_edge_weights:
    edge_labels = nx.get_edge_attributes(G, "weight")
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

  # 2. Draw the nodes of all the paths
  all_paths_nodes = set()
  for path in paths_data:
    all_paths_nodes.update(path[0])
  # Change the font of the labels of the path nodes and restore alpha=None.
  for node, (x, y) in pos.items():
    if node in all_paths_nodes:
      plt.text(x, y, node, fontsize=19, ha='center', va='center')
  nx.draw_networkx_nodes(G, pos=pos,
                         nodelist=all_paths_nodes, node_size=path_node_size,
                         edgecolors='k', node_color="deepskyblue", alpha=0.9)

  # 3. Draw the paths
  colors = iter(COLORS)
  width_step = 6.5
  last_path_width = 4
  first_path_width = max(last_path_width + (len(paths_data) - 1) * width_step,
                         8)
  for i, path in enumerate(paths_data):
    try:
      color = next(colors)
    except StopIteration:
      warn("Up to 8 paths can be plotted. Try the -v option, to print all the"
           " generated paths.")
      break
    label = path_label(path, i + 1, mode.get("failing", "edges"))
    path_edges_sequence = list(zip(path[0], path[0][1:]))
    # arrows=False, arrowsize=20, arrowstyle='fancy',
    # min_source_margin=1, min_target_margin=1,
    # from matplotlib.patches import ConnectionStyle
    # connectionstyle=ConnectionStyle("Arc3", rad=0.2),
    nx.draw_networkx_edges(G, pos=pos, edgelist=path_edges_sequence,
                           edge_color=color, alpha=0.8, arrows=False,
                           width=first_path_width - i * width_step,
                           label=label)

    # Mark the disconnceted edge or node with an ×.
    if mode.get("failing") == "nodes":
      if (len(path) > 2) and (path[3] not in [None, [None]]):
        if hasattr(path[3], "__len__"):
          nodelist = path[3]
        else:
          nodelist = [path[3]]
        nx.draw_networkx_nodes(G, pos=pos, nodelist=nodelist,
                               node_color=color, node_shape='x',
                               node_size=failed_node_size, linewidths=5)
    elif mode.get("failing") == "edges":
      # Check for the case of the absolute shortest path, where there is no
      # disconnected edge.
      if (len(path) > 2) and (path[3] is not None):  # ✕×✗
        nx.draw_networkx_edge_labels(G, pos, edge_labels={path[3]: '×'},
                                     font_size=60, font_color=color,
                                     bbox=dict(alpha=0), rotate=False)
    elif mode.get("failing") is None:
      pass
    else:
      raise ValueError("failing should be 'edges', 'nodes' or None")

  if (len(path) > 2) and (path[3] is not None):
    online_status = "on-line" if mode.get('online') else "off-line"
    frame_title = ("Replacement-paths\n"
                   f"mode: {online_status} / failing {mode.get('failing')}")
  else:
    frame_title = "\nk-shortest paths"

  frame_title += (f"\n#nodes: {G.number_of_nodes()}   "
                  f"#edges: {G.number_of_edges()}   "
                  f"#paths: {len(paths_data)}")
  plt.title(frame_title, fontsize=title_fontsize)
  leg = plt.legend(fontsize=legend_fontsize)
  leg.get_frame().set_alpha(None)
  leg.get_frame().set_facecolor((1, 1, 1, 0.5))

  plt.tight_layout()
  xmin, xmax, ymin, ymax = _xylimits(pos)
  plt.xlim(xmin, xmax)
  plt.ylim(ymin, ymax)

  if save_graph:
    date_n_time = str(datetime.now())[:19]
    date_n_time = date_n_time.replace(':', '-').replace(' ', '_')
    file_name = f"graph_vis_{date_n_time}.png"
    plt.savefig(os.path.join(os.getcwd(), file_name), dpi=fig.dpi)
  if show_graph:
    plt.show()
示例#46
0
query2 = "von"

for tree in trees:
    id = dict([(u, d['id']) for u, d in tree.nodes(data=True)])

    for token, i in id.items():
        if token == query2:
            print("Token", i, ":", token)
            print(nx.info(tree, token))

print("\n")

# visualise a sentence

query3 = 33

dg = trees[query3]
print("Dependency Tree for Sentence", query3, ":")
print(nx.info(dg))
print("Token IDs:",
      nx.get_node_attributes(dg, 'id'))  # mapping back into dataframe

pos = nx.spectral_layout(dg)
edge_labels = dict([((u, v), d['rel']) for u, v, d in dg.edges(data=True)])
nx.draw_networkx_edge_labels(dg, pos, edge_labels=edge_labels)
nx.draw_networkx(dg, pos, with_labels=True)

plt.axis('off')
plt.show()
示例#47
0
def state_retrieval_vis(G,
                        paths_data,
                        visited_nodes_forward,
                        visited_nodes_reverse,
                        retrieved_nodes_forward,
                        retrieved_nodes_reverse,
                        visited_after_retrieval,
                        meeting_edge: tuple,
                        mode,
                        random_seed,
                        layout_seed,
                        show_graph,
                        save_graph):
  if save_graph:
    figsize = (10 * 1.8, 10)
    dpi = 200
    title_fontsize = 23
    legend_fontsize = 21
  else:
    figsize = (8 * 1.8, 8)
    dpi = 100
    title_fontsize = 18
    legend_fontsize = 16

  k_0 = 18
  fig = plt.figure(figsize=figsize, dpi=dpi)
  pos = nx.spring_layout(G,
                         seed=layout_seed,
                         k=k_0 / sqrt(G.number_of_nodes()))

  # 1. Draw the graph
  # Exclude the visited nodes
  nodelist = set(G.nodes()).difference(visited_nodes_forward) \
                           .difference(visited_nodes_reverse) \
                           .difference(visited_after_retrieval)
  node_size, path_node_size, failed_node_size = _node_sizes(G)
  nx.draw_networkx(G, pos, node_size=node_size, width=0.3, alpha=0.3,
                   nodelist=nodelist, with_labels=False, arrows=False)

  # 2. Draw the forward state
  if visited_nodes_forward:
    nx.draw_networkx_nodes(G, pos=pos, nodelist=visited_nodes_forward,
                           node_color='#2c051a', alpha=0.8, node_size=2900,
                           linewidths=0, label="forward visited")
    nx.draw_networkx_nodes(G, pos=pos, nodelist=retrieved_nodes_forward,
                           node_color='limegreen', alpha=0.7, node_size=2000,  # #132226
                           linewidths=0, label="forward retrieved")

  # 3. Draw the reverse state
  # background        : foreground
  # ------------------------------
  # 603F83FF 343148FF : C7D3D4FF
  # 192e5b            : 72a2c0
  # 00539CFF          : 9CC3D5FF B1624EFF A2A2A1FF f2eaed
  nx.draw_networkx_nodes(G, pos=pos, nodelist=visited_nodes_reverse,
                         node_color='navy', alpha=0.75, node_size=2900,
                         linewidths=0, label="reverse visited")

  nx.draw_networkx_nodes(G, pos=pos, nodelist=retrieved_nodes_reverse,
                         node_color='#f2eaed', alpha=0.8, node_size=2000,
                         linewidths=0, label="reverse retrieved")

  # 4. Draw the visited after retrieval
  nx.draw_networkx_nodes(G, pos=pos, nodelist=visited_after_retrieval,
                         node_color='orangered', alpha=0.8, node_size=2000,
                         linewidths=0, label="visited after retrieval")

  # 5. Draw the nodes of all the paths
  all_paths_nodes = set()
  for path in paths_data:
    all_paths_nodes.update(path[0])
  # Change the font of the labels of the path nodes and restore alpha=None.
  for node, (x, y) in pos.items():
    if node in all_paths_nodes:
      plt.text(x, y, node, fontsize=20, ha='center', va='center')
  nx.draw_networkx_nodes(G, pos=pos,
                         nodelist=all_paths_nodes, node_size=path_node_size,
                         edgecolors='k', node_color="deepskyblue")

  # 6. Draw the paths
  colors = iter(['mediumblue', 'r'])
  edgewidth_max = 12
  edgewidth_step = 7
  for i, path in enumerate(paths_data):

    color = next(colors)
    label = path_label(path, i + 1, mode["failing"])
    path_edges_sequence = list(zip(path[0], path[0][1:]))
    nx.draw_networkx_edges(G, pos=pos, edgelist=path_edges_sequence,
                           edge_color=color, alpha=0.8, arrows=False,
                           width=edgewidth_max - edgewidth_step * i,
                           label=label)

    # Mark the disconnceted edge or node with an ×.
    if mode["failing"] == "nodes":
      if (len(path) > 2) and (path[3] not in [None, [None]]):
        if hasattr(path[3], "__len__"):
          disconnected = path[3]
        else:
          disconnected = [path[3]]
        nx.draw_networkx_nodes(G, pos=pos, nodelist=disconnected,
                               node_color=color, node_shape='x',
                               node_size=failed_node_size, linewidths=5)
    elif mode["failing"] == "edges":
      # Check for the case of the absolute shortest path, where there is no
      # disconnected edge.
      # if path[3] == meeting_edge:
      #   x_pos = 0.5
      # else:
      #   x_pos = 0.51
      x_pos = 0.5
      if (len(path) > 2) and (path[3] is not None):  # ✕×✗
        nx.draw_networkx_edge_labels(G, pos, edge_labels={path[3]: '×'},
                                     font_size=80, font_color=color,
                                     label_pos=x_pos, bbox=dict(alpha=0),
                                     rotate=False)
    elif mode["failing"] is None:
      pass
    else:
      raise ValueError("failing should be 'edges', 'nodes' or None")

  # 7. Draw the meeting edge
  nx.draw_networkx_edges(G, pos=pos, edgelist=[meeting_edge],
                         edge_color="aqua", alpha=0.9, arrows=False,
                         width=edgewidth_max - edgewidth_step,
                         label=f"meeting edge: {meeting_edge}")

  leg = plt.legend(fontsize=legend_fontsize)
  leg.get_frame().set_alpha(None)
  leg.get_frame().set_facecolor((1, 1, 1, 0.5))
  online_mode = "online" if mode["online"] else "offline"
  plt.title(("State retrieval\n"
             f"n: {G.number_of_nodes()}"
             f"   m: {G.number_of_edges()}"
             f"   mode: {online_mode}"),
            fontsize=title_fontsize)

  plt.tight_layout()
  xmin, xmax, ymin, ymax = _xylimits(pos)
  plt.xlim(xmin, xmax)
  plt.ylim(ymin, ymax)

  if ((visited_nodes_forward == retrieved_nodes_forward)
          and (visited_nodes_reverse == retrieved_nodes_reverse)):
    failed_edge = "_me"
  else:
    failed_edge = ""

  if save_graph:
    file_name = (f"state_retrieval_vis_k_0_{k_0}_s_{random_seed}"
                 f"_l_{layout_seed}_e_{paths_data[1][3][0]}_dpi_{dpi}"
                 "{failed_edge}.png")
    plt.savefig(os.path.join(os.getcwd(), file_name), dpi=fig.dpi)
  if show_graph:
    plt.show()
示例#48
0
 def draw_mas_sys(self):
     plt.figure()
     nx.draw_networkx(self.G)
示例#49
0
def show_graph(G):
    nx.draw_networkx(G,
                     pos=nx.kamada_kawai_layout(G),
                     with_labels=False,
                     node_size=100)
    plt.show()
示例#50
0
def plot_search_sphere(G,
                       visited,
                       path,
                       show_graph=True,
                       save_graph=False,
                       layout_seed=0,
                       visited_reverse=None,
                       meeting_edge_head=None):
  """Plots the visited nodes of the uni/bi-directional search."""
  if save_graph:
    figsize = (10 * 1.8, 10)
    dpi = 200
    title_fontsize = 22
    legend_fontsize = 20
  else:
    figsize = (8 * 1.8, 8)
    dpi = 100
    title_fontsize = 18
    legend_fontsize = 16

  visited_nodes_forward = visited_nodes(visited, path[0])
  num_visited_forward = len(visited_nodes_forward)
  if visited_reverse is None:
    algorithm = "Dijkstra's algorithm"
    file_name = "dijkstra"
    path_forward = path
  else:
    algorithm = "Bidirectional Dijkstra's algorithm"
    file_name = "bidirectional"
    visited_nodes_reverse = visited_nodes(visited_reverse, path[-1])
    num_visited_reverse = len(visited_nodes_reverse)
    meeting_edge_head_idx = path.index(meeting_edge_head)
    path_forward = path[:meeting_edge_head_idx]
    path_reverse = path[meeting_edge_head_idx:]

  fig = plt.figure(figsize=figsize, dpi=dpi)
  pos = nx.spring_layout(G,
                         seed=layout_seed,
                         k=72 / sqrt(G.number_of_nodes()))

  # 1. Draw the graph
  node_size, path_node_size, failed_node_size = _node_sizes(G)
  nx.draw_networkx(G, pos, node_size=node_size, width=0.15, alpha=0.3,
                   with_labels=False, arrows=False)

  # 2. Draw the visited nodes
  nx.draw_networkx_nodes(G, pos=pos, nodelist=visited_nodes_forward,
                         node_color='goldenrod', node_size=800, linewidths=0,
                         label="forward search", alpha=0.85)
  if visited_reverse is not None:
    nx.draw_networkx_nodes(G, pos=pos, nodelist=visited_nodes_reverse,
                           node_color='g', node_size=800, linewidths=0,
                           label="reverse search", alpha=0.8)

  # 3. Draw the path-nodes
  for node, (x, y) in pos.items():
    if node in path:
      plt.text(x, y, node, fontsize=20, ha='center', va='center')

  nx.draw_networkx_nodes(G, pos=pos, nodelist=path_forward, edgecolors='k',
                         node_size=path_node_size, node_color="deepskyblue")
  if visited_reverse is not None:
    nx.draw_networkx_nodes(G, pos=pos, nodelist=path_reverse, edgecolors='k',
                           node_size=path_node_size, node_color="deepskyblue")

  # 4. Draw the path
  if visited_reverse:
    label = f"forward subpath: {path_forward}"
  else:
    label = f"path: {path_forward}"
  path_edges_sequence = list(zip(path_forward[:-1], path_forward[1:]))
  nx.draw_networkx_edges(G, pos=pos, edgelist=path_edges_sequence,
                         edge_color='k', arrows=False,
                         width=10, label=label)
  if visited_reverse is not None:
    # then, draw the reverse subpath
    path_edges_sequence = list(zip(path_reverse[:-1], path_reverse[1:]))
    nx.draw_networkx_edges(G, pos=pos, edgelist=path_edges_sequence,
                           edge_color='mediumblue', arrows=False,
                           width=10, label=f"reverse subpath: {path_reverse}")
    meeting_edge = [(path_forward[-1], path_reverse[0])]
    nx.draw_networkx_edges(G, pos=pos, edgelist=meeting_edge,
                           edge_color='r', arrows=False,
                           width=10, label=f"meeting edge: {meeting_edge[0]}")

  if visited_reverse is None:
    num_visited_total = num_visited_forward
  else:
    num_visited_total = num_visited_forward + num_visited_reverse
  frame_title = (f"{algorithm} search space\n"
                 f"n: {G.number_of_nodes()}"
                 f"   m: {G.number_of_edges()}"
                 f"   nodes visited: {num_visited_total}")
  plt.title(frame_title, fontsize=title_fontsize)
  plt.legend(fontsize=legend_fontsize)
  plt.tight_layout()

  if save_graph:
    date_n_time = str(datetime.now())[:19]
    date_n_time = date_n_time.replace(':', '-').replace(' ', '_')
    file_name = (f"search_sphere_{file_name}_{date_n_time}.png")
    plt.savefig(os.path.join(os.getcwd(), file_name), dpi=fig.dpi)
  if show_graph:
    plt.show()
示例#51
0
    def graph_to_networkx(self, idx, data):
        #non-directed,non-weighted,normal
        edge_labels = {}
        if self._s2 == 'non-directed' and self._s3 == 'non-weighted' and self._s4 == 'normal':
            n, m = map(int, data.pop(0).split())
            g = nx.Graph()
            g.add_nodes_from(list(range(idx, n + idx)))

            for i in range(m):
                a, b = map(int, data[i].split())
                g.add_edge(a, b)

        ###non-directed,weighted,normal
        if self._s2 == 'non-directed' and self._s3 == 'weighted' and self._s4 == 'normal':
            n, m = map(int, data.pop(0).split())
            g = nx.Graph()
            g.add_nodes_from(list(range(idx, n + idx)))

            for i in range(m):
                a, b, c = map(int, data[i].split())
                g.add_edge(a, b, weight=c)
                edge_labels[(a, b)] = c

        ###directed,non-weighted,normal
        if self._s2 == 'directed' and self._s3 == 'non-weighted' and self._s4 == 'normal':
            n, m = map(int, data.pop(0).split())
            g = nx.DiGraph()
            g.add_nodes_from(list(range(idx, n + idx)))
            for i in range(m):
                a, b = map(int, data[i].split())
                g.add_edge(a, b)

        ###directed,weighted,normal
        if self._s2 == 'directed' and self._s3 == 'weighted' and self._s4 == 'normal':
            n, m = map(int, data.pop(0).split())
            g = nx.DiGraph()
            g.add_nodes_from(list(range(idx, n + idx)))
            for i in range(m):
                a, b, c = map(int, data[i].split())
                g.add_edge(a, b, weight=c)
                edge_labels[(a, b)] = c

        ###non-directed,non-weighted,martrix
        if self._s2 == 'non-directed' and self._s3 == 'non-weighted' and self._s4 == 'martrix':
            n = int(data.pop(0))
            data = [list(map(int, d.split())) for d in data]
            g = nx.Graph()
            g.add_nodes_from(list(range(idx, n + idx)))
            for i in range(n):
                for j in range(n):
                    if data[i][j]:
                        g.add_edge(i + idx, j + idx)
        ###non-directed,weighted,martrix
        if self._s2 == 'non-directed' and self._s3 == 'weighted' and self._s4 == 'martrix':
            n = int(data.pop(0))
            data = [list(map(int, d.split())) for d in data]
            g = nx.Graph()
            g.add_nodes_from(list(range(idx, n + idx)))
            for i in range(n):
                for j in range(n):
                    if data[i][j] != 0:
                        g.add_edge(i + idx, j + idx, weight=data[i][j])
                        edge_labels[(i + idx, j + idx)] = data[i][j]

        ###directed,non-weighted,martrix
        if self._s2 == 'directed' and self._s3 == 'non-weighted' and self._s4 == 'martrix':
            n = int(data.pop(0))
            data = [list(map(int, d.split())) for d in data]
            g = nx.DiGraph()
            g.add_nodes_from(list(range(idx, n + idx)))
            for i in range(n):
                for j in range(n):
                    if data[i][j] == 1:
                        g.add_edge(i + idx, j + idx)

        ###directed,weighted,martrix
        if self._s2 == 'directed' and self._s3 == 'weighted' and self._s4 == 'martrix':
            n = int(data.pop(0))
            data = [list(map(int, d.split())) for d in data]
            g = nx.DiGraph()
            g.add_nodes_from(list(range(idx, n + idx)))
            for i in range(n):
                for j in range(n):
                    if data[i][j] != 0:
                        g.add_edge(i + idx, j + idx, weight=data[i][j])
                        edge_labels[(i + idx, j + idx)] = data[i][j]

        fig = plt.figure(figsize=(15, 15))
        pos = nx.spring_layout(g, k=self._k)
        nx.draw_networkx(g,
                         pos,
                         node_size=self._node_size,
                         node_color=self._node_color,
                         node_shape=self._node_shape,
                         width=self._width,
                         edge_color=self._edge_color,
                         alpha=self._alpha,
                         font_color=self._font_color,
                         font_weight=self._font_weight,
                         font_size=self._font_size)
        if edge_labels:
            nx.draw_networkx_edge_labels(g,
                                         pos,
                                         edge_labels=edge_labels,
                                         font_size=self._font_size - 2)
        plt.axis('off')
        return fig
示例#52
0
import networkx as nx
from networkx.algorithms import community
import matplotlib.pyplot as plt

# 1.Genereating network

G = nx.barabasi_albert_graph(100, 3)

# 2.Drawing degree distribution

pos = nx.spring_layout(G)
nx.draw_networkx(G, pos, with_labels=True)
plt.show()

# 3.Finding all communities    (I used Louvain Modularity Algorithm.)

communities = list(community.greedy_modularity_communities(G))

# 4.Number of communities

print(f"There are {len(communities)} communities.")

# 5.Naming communities    (I assigned all the communities that I created into a array called community. When I want to access it, I will do this using the index value.)

community = []
for frozenset in communities:
    community.append(list(frozenset))

# 6.Print the size and the node labels in each community

i = 1
示例#53
0
def perform_test(test_set):
    '''
    test_set form: {'tree': name_of_example OR name_of_pickled_tree,
                    'viz': true or false,
                    'classification': [TreeNN, TreeInsert]}
    '''      
    tree_built = False
    query_results = {}

    # Define a test tree
    if test_set['tree'] == "wiki":

        print "\nBuilding Tree with Wikipedia example...\n"
        labels = ['a', 'b', 'c', 'q', 'e'] #d is query protein - q
        class_map = {'a':'class1','b':'class1','c':'class2','q':'query','e':'class3'}
        dist_matrix = pd.DataFrame([[0, 5,  9,  9,  8],
                                   [5, 0,  10, 10, 9],
                                   [9, 10, 0,  8,  7],
                                   [9, 10, 8,  0,  3],
                                   [8, 9,  7,  3,  0]],
                               index=labels, columns=labels)
        query_name = 'q'

    elif test_set['tree'] == "protein_database":

        print "\nBuilding Tree with data/distance_matrix.csv & data/id_lookup.csv...\n"
        dist_matrix = read_distance_csv('./data/distance_matrix.csv')
        class_map = read_classes_csv('./data/id_lookup.csv')
        query_name = class_map.keys()[0]
        
    else:

        print "\nUsing built tree from file: " + test_set['tree'] + " ...\n"
        njt = pickle.load(open(test_set['tree'], "rb" ))
        query_name = njt.class_map.keys()[0]
        tree_built=True

    # Build the test tree
    if not tree_built:
        njt = NJTree()
        njt.build(dist_matrix, class_map, myClusterNaming)

    # Record query info 
    query_results['Protein'] = query_name
    truth_class = njt.class_map[query_name]
    query_results['Truth_Class'] = truth_class
    print "QUERY: ", query_name
    print "TRUTH: ", truth_class

    # Visualize tree
    # TODO add key to the viz
    if test_set['viz']:
        labels = {i[0]: i[1]['c'] for i in njt.tree.nodes(data=True)}
        layout = nx.spring_layout(njt.tree)
        all_node_classes = nx.get_node_attributes(njt.tree, 'c')
        # Get rid of internal nodes
        node_classes = {k: v for k,v in all_node_classes.items() if len(v) > 0}
        unique_classes = list(Set(node_classes.values()))
        unique_colors = plt.cm.Set3(np.linspace(0, 1, len(unique_classes)))
        color_map = {unique_classes[i] : unique_colors[i] for i in range(len(unique_colors))}
        node_list = node_classes.keys()
        node_colors = [color_map[njt.tree.node[node]['c']] for node in node_list]
        # Add legend
        f = plt.figure(1)
        ax = f.add_subplot(1,1,1)
        for cls in color_map:
            ax.plot([0], [0], '-', color=color_map[cls], label=cls, linewidth=10)
        
        #nx.draw_networkx(njt.tree, pos=layout, with_labels=True) #ID labels
        #nx.draw_networkx(njt.tree, with_labels=True, labels=labels, node_size=100) #class labels
        nx.draw_networkx(njt.tree, with_labels=False, node_size=150,
                         nodelist=node_list, node_color=node_colors, ax=ax) #no labels
        plt.axis('off')
        f.set_facecolor('w')
        plt.legend(loc='upper left')
        f.tight_layout()
        plt.show()

    # Classify 
    classifications = [i.lower() for i in test_set['classification']]

    if "treenn" in classifications:

        query_class = njt.classify_treeNN(query_name)
        query_results['TreeNN'] = query_class
        query_results['TreeNN_Correct'] = (query_class == truth_class)
        print '\nQUERY CLASS (TreeNN): ', query_class

    if "treeinsert" in classifications:

        query_class = njt.classify_treeInsert(query_name, myClusterNaming)
        query_results['TreeInsert'] = query_class
        query_results['TreeInsert_Correct'] = (query_class == truth_class)
        print '\nQUERY CLASS (TreeInsert): ', query_class

    return njt, query_results
示例#54
0
def Partition_F(name1, xxx, k):
    # name1 = 'E:\\脑电python3\\分区块数据\\'
    name2 = 'data%d.pdf' % (k)
    name = name1 + name2
    with PdfPages(name) as pdf:
        data = np.nonzero(xxx)
        row = data[0]
        col = data[1]
        di = zip(row, col)
        list_di = list(di)
        G = nx.Graph()
        G.add_edges_from(list_di)
        # print("list_di---", list_di)
        # print("type(list_di[0])---", type(list_di[0]))
        # print("type(list_di[0][0])---", type(list_di[0][0]))

        # 将节点写入txt文件
        for l1 in list_di:
            # print("l1---", l1)
            # print("l2---", l2)
            num1 = int(l1[0])
            num2 = int(l1[1])
            # list_num = [num1, num2]
            # print(list_num)
            fp = open("E:\\脑电python3\\ceshi\\node.txt", "a+")
            fp.writelines(str(num1)+" "+str(num2)+" "+"1" + "\n")
            # fp.writelines(str(list_num) + "\n")
        fp.close()

        # 画圆
        x1 = y1 = np.arange(-1, 15, 0.1)
        x1, y1 = np.meshgrid(x1, y1)
        plt.contour(x1, y1, (x1 - 7) ** 2 + (y1 - 7) ** 2, [49])
        plt.axis('scaled')
        # plt.show()

        # 统计节点的度
        list_degree = G.degree()
        print("节点的度:", list_degree)
        d1 = list_degree[0]
        print(d1)

        # 画网络图
        pos = [(5.5, 13.5), (5, 13), (4.5, 11.5), (3, 12.5), (2, 9.5),
               (5.5, 9.5), (3, 7), (0, 7), (2, 5), (5.5, 5),
               (4.5, 2.5), (3, 2), (5, 1.5), (6, 0.5), (7, 0),
               (7, 3), (8.5, 13.5), (9, 13), (7, 11), (9.5, 11.5),
               (11, 12.5), (12, 9.5), (8.5, 9.5), (7, 7), (11, 7),
               (14, 7), (12, 5), (8.5, 5), (9.5, 2.5), (11, 2),
               (9, 1.5), (8, 0.5)]
        nx.draw_networkx(G, pos, cmap=plt.cm.Blues, with_labels=True)
        plt.title('Page1')
        pdf.savefig()  # saves the current figure into a pdf page
        plt.close()

        # 实现网络划分(计算Q)
        # 画圆
        x1 = y1 = np.arange(-1, 15, 0.1)
        x1, y1 = np.meshgrid(x1, y1)
        plt.contour(x1, y1, (x1 - 7) ** 2 + (y1 - 7) ** 2, [49])
        plt.axis('scaled')
        # 分类
        # part = community.best_partition(G)
        # print("part-----", part)
        # mod = community.modularity(part, G)
        # print("mod-----", mod)
        # values = [part.get(node) for node in G.nodes()]
        # print("values-----", values)
        # nx.draw_networkx(G, pos, node_color=values, with_labels=True)
        # # plt.savefig('E:\\脑电python3\\分区块数据\\bbb.jpg')
        # # plt.show()
        # plt.title('Page2')
        # pdf.savefig()  # saves the current figure into a pdf page
        # plt.close()
        # values = []
        mod, values = FastUnfolding()
        nx.draw_networkx(G, pos, node_color=values, with_labels=True)
        plt.title('Page2')
        pdf.savefig()  # saves the current figure into a pdf page
        plt.close()
        # print("mod-----------", mod)
        # print("values-----------", values)

        # 过程
        x1 = y1 = np.arange(-1, 15, 0.1)
        x1, y1 = np.meshgrid(x1, y1)
        plt.contour(x1, y1, (x1 - 7) ** 2 + (y1 - 7) ** 2, [49])
        plt.axis('scaled')

        values2 = [0, 0, 0, 0, 1, 2, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 3, 3, 3, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5]
        nx.draw_networkx(G, pos, node_color=values2, with_labels=True)
        plt.title('Page3')
        pdf.savefig()  # saves the current figure into a pdf page
        plt.close()


        return mod
示例#55
0
def is_eorbit_pair(g, e, f):
    return is_same_degrees(g, e, f) and is_same_endpoints_neighbors(g, e, f)


def is_eorbit_group(g, s):
    if len(s) == 1:
        return True
    return all(is_eorbit_pair(g, e, f) for e, f in combinations(s, 2))


def edge_orbits(g):
    for ss in all_partitions(g, list(g.edges())):
        if all(is_eorbit_group(g, s) for s in ss):
            return ss


if __name__ == '__main__':
    g, pos = gen()
    print(vertex_orbits(g))
    print(edge_orbits(g))

    #    matplotlib.use('module://backend_ipe')
    #    isy = "/Applications/Ipe.app/Contents/Resources/styles/basic.isy"
    #    matplotlib.rcParams['ipe.stylesheet'] = isy
    nx.draw_networkx(g, pos, node_color='#ff9999')
    plt.gca().set_aspect('equal')
    plt.gca().axis('off')
    plt.show()
#    plt.savefig('orbits_01.ipe', format='ipe')
示例#56
0
from parse import parse
import networkx as nx

pattern = 'Step {start} must be finished before step {stop} can begin.'
sleigh_steps = nx.DiGraph()

for line in open('input.txt'):
    result = parse(pattern, line)
    sleigh_steps.add_edge(result['start'], result['stop'])

print(''.join(nx.lexicographical_topological_sort(sleigh_steps)))
# for order in nx.all_topological_sorts(sleigh_steps):
#     print(order)
# print(''.join(min(nx.all_topological_sorts(sleigh_steps))))

import matplotlib.pyplot as plt
pos = nx.nx_agraph.graphviz_layout(sleigh_steps, prog='dot')
nx.draw_networkx(sleigh_steps, pos=pos)
plt.show()
示例#57
0
        Build the keyword graph. 
        Arguments:
            cooccuranceThreshold : If the cooccurances of two keywords is above
            coocuranceThreshold, there is an edge between the nodes represented
            by the keywords. 
            Default value is 1
        Returns:
            A networkx graph with keywords as nodes and there is an edge between two nodes
            if their similarity value is greater than similarityThreshold.
        """
        docsForWords = self.docsContainingWords()
        h = nx.Graph()
        for w in self.vocabalury():
            h.add_node(w)

        for w1 in h.nodes():
            for w2 in h.nodes():
                weight = len(set(docsForWords[w1]) & set(docsForWords[w2]))
                if (weight > cooccuranceThreshold):
                    h.add_edge(w1, w2, weight=weight)

        return h


if __name__ == '__main__':
    grapher = TextGraph(open(sys.argv[1]))
    g = grapher.sentenceGraph()
    subgraphs = nx.connected_component_subgraphs(g)
    nx.draw_networkx(subgraphs[0], with_labels=False)
    plt.show()
示例#58
0
    def build(self, dist_matrix, class_map, cluster_naming_function):
        """Builds this classification tree via the neighbor-joining method.

        Args:
            dist_matrix (pandas.DataFrame): Matrix of pairwise distances labelled with element IDs.
            class_map (dict): Dictionary where keys are element IDs and values are class labels.
            cluster_naming_function (function): Function to assign new names to clusters based on 
                nodes to be clustered and the cluster dictionary in form myFunct(node1, node2, cluster_map).
        """
        # Update attributes
        self.orig_dist_matrix = dist_matrix 
        self.class_map = class_map 
        self.work_dist_matrix = dist_matrix

        # Get number of elements
        n = dist_matrix.shape[0]

        if PROGRESS:
            print 'Starting tree build now!'

        # Loop through n-3 elements & add nodes in tree
        for i in range(n - 3):

            if DEBUG:
                print 'Distance Matrix'
                pprint(self.work_dist_matrix)
                print

            # Calculate q_matrix matrix from distances
            q_matrix = _calculate_q_matrix(self.work_dist_matrix)
            
            if DEBUG:
                print 'Q matrix:'
                pprint(q_matrix)
                print

            # Find pair of elements (i,j) where q_matrix(i,j) has the lowest value
            (min_col, min_row) = _find_min_pair(q_matrix)

            # Add nodes i,j, and cluster node of i and j to this tree
            # And update working distance matrix accordingly
            new_cluster_name = cluster_naming_function(min_row, min_col, self.cluster_map)
            self.cluster_leaves(min_row, min_col, new_cluster_name) 

            if DEBUG:
                print 'Tree:'
                pprint(nx.clustering(self.tree))
                pprint(self.cluster_dictionary)
                print '\n\n'
            
            # View graph after each step for debugging
            if VIEW_ALL:
                labels = {i[0]: i[0]+'/'+i[1]['c'] for i in njt.tree.nodes(data=True)}
                layout = nx.spring_layout(njt.tree)
                nx.draw_networkx(njt.tree, pos=layout, with_labels=True, labels=labels) #class labels
                plt.show()

            if PROGRESS:
                print str(i + 1) + " down, " + str(n-i-4) + " to go..."
            
        # Add remaining branch lengths and nodes from working distance matrix to this tree 
        previous_cluster = new_cluster_name
        mid_edge_length = 0.5 * (self.work_dist_matrix.iat[0, 1]
                              + self.work_dist_matrix.iat[0, 2]
                              - self.work_dist_matrix.iat[1, 2])
        (node1, node2) = (self.work_dist_matrix.columns[0], self.work_dist_matrix.columns[1])
        new_cluster = cluster_naming_function(node1, node2, self.cluster_map)
        self.cluster_leaves(node1, node2, new_cluster)
        # Viz only scales based on a weight attribute, so we set that as the length
        self.tree.add_edge(previous_cluster, new_cluster, length=mid_edge_length, weight=mid_edge_length)

        if DEBUG:
            print 'Final tree:'
            pprint(nx.clustering(self.tree))
            pprint(self.cluster_dictionary)
def main():
    """
    Main method to perform part A ,B C
    :return:
    """
    # Webscraping for names
    print("reading names from web..")
    readNames("boy", "boys.dat")
    readNames("girl", "girls.dat")
    print("done...")
    mean = np.empty([10, 150])
    mname = dl.yieldName('male')
    fname = dl.yieldName('female')

    for j in range(1, 11):
        print("")
        print("**************************************************")
        print("Trial No.{}".format(str(j)))
        start_year = 0
        dolph_list = []
        mothers = []
        fathers = []
        dolphinPop_75 = []

        populations = np.empty(150)
        years = np.empty(150)
        births = 0

        dol1 = Dolphins(next(mname), 'male', 'abc', 'xys', 0)
        dol2 = Dolphins(next(fname), 'female', 'ab', 'xyf', 0)
        dol3 = Dolphins(next(mname), 'male', 'a', 'f', 0)
        dol4 = Dolphins(next(fname), 'female', 'b', 'y', 0)

        dolph_list.append(dol1)
        dolph_list.append(dol2)
        dolph_list.append(dol3)
        dolph_list.append(dol4)

        for year in range(150):
            years[year] = year
            alive_list = alive_lst(year, dolph_list)

            pop = len(alive_list)
            populations[year] = pop

            male_alive = []
            female_alive = []

            for dol in alive_list:
                if dol.sex == 'male':
                    male_alive.append(dol)
                else:
                    female_alive.append(dol)

            update_all_procreation(year, male_alive)
            update_all_procreation(year, female_alive)

            p_mothers = []
            p_fathers = []
            for f in female_alive:
                if f.years_since_procreation >= 5 and f.age > 6:
                    p_mothers.append(f)
            for m in male_alive:
                if m.years_since_procreation >= 5 and f.age > 6:
                    p_fathers.append(m)

            mothers = []
            fathers = []
            breeding = len(p_fathers) + len(p_mothers)
            for mom in p_mothers:
                if len(p_fathers) != 0:
                    dad = random.sample(p_fathers, 1)[0]
                    if mom.request_procreation(dad):
                        if random.random() > 0.5:  # deciding the gender
                            sex = 'male'
                            name = next(mname)
                        else:
                            sex = 'female'
                            name = next(fname)
                        new = Dolphins(name, sex, mom, dad, year)
                        dolph_list.append(new)
                        mom.children.append(new)
                        dad.children.append(new)
                        mothers.append(mom)
                        fathers.append(dad)
                        births += 1
            if year != 5 or year != 6:
                update_all_procreation(year, alive_list)

            if year == 0:
                print("##################################################")
                print('entering year 0 with 4 dolphins, with 0 breeding.')
            if year % 25 == 0 and year != 100 and year != 0:
                print("##################################################")
                print("entering year ", year, " with ", pop,
                      " dolphins, with ", breeding, "breeding")
            if year == 100:
                print("##################################################")
                print("entering year ", year, " with ", pop,
                      " dolphins, with ", breeding, "breeding")
            if year == 75:
                dolphinPop_75 = dolphinPop_75 + alive_list
            if year == 101:
                print("at year ", year - 1, " there are ", pop,
                      " living dolphins.")
                print("there have been", births, "births, in total.")

            if year == 149:
                print("##################################################")
                print("At year, ", year, " there are ", pop,
                      " living dolphins")
        mean[j - 1] = populations

    # For calculating the mean
    mean_popopulation = np.mean(mean, axis=0)
    # For calculating the standard deviation
    std_population = np.std(mean, axis=0)
    y1 = mean_popopulation + std_population
    y2 = mean_popopulation - std_population

    plt.plot(years, mean_popopulation, 'b')
    plt.xlabel("Years")
    plt.ylabel("Number of Living Dolphins")
    plt.title("Average population and standard deviation from 10 trials")
    plt.fill_between(years, y1, y2, facecolor='red')
    plt.savefig("population_growth.pdf")
    plt.show()

    # for plotting the genology tree
    rand = random.randrange(0, 10)
    dolph_pop = []
    dolphin_pop = dolphinPop_75

    char = (random.sample(dolphin_pop, 1))[0]

    mom_char = char.mother
    dad_char = char.father

    mom_half = []
    dad_half = []
    full_sib = []
    for elem in dolphin_pop:
        if elem.mother == mom_char and elem.father == dad_char and elem != char:
            full_sib.append(elem)
        elif elem.mother == mom_char and elem != char:
            mom_half.append(elem)
        elif elem.father == dad_char and elem != char:
            dad_half.append(elem)

    # Creates graph for geneology.
    # and plots the graph accordingly
    gen = nx.Graph()
    gen.add_node(mom_char, pos=(0, 3))  # adding mother node
    gen.add_node(dad_char, pos=(3, 3))  # adding father node
    xheight = .5
    xfloor = 0
    for j in dolphin_pop:
        if j in mom_half:
            gen.add_node(j, pos=(xheight, 1))
            gen.add_edge(j, mom_char)
            xheight += 2
        if j in dad_half:
            gen.add_node(j, pos=(xheight, 1))
            gen.add_edge(j, dad_char)
            xheight += 2
        if j in full_sib:
            gen.add_node(j, pos=(xfloor, 2))
            gen.add_edge(j, mom_char)
            gen.add_edge(j, dad_char)
            xfloor += 2
    pos = nx.get_node_attributes(gen, 'pos')
    nx.draw_networkx(gen, pos)
    plt.title(char.name + "'s Family")
    plt.axis('off')
    plt.savefig("genealogy.pdf")
    plt.show()
示例#60
0
with open(filename) as f:
    # Create a csv reader object.
    reader = csv.reader(f)
    
    # Store the latitudes and longitudes in the appropriate lists.
    i = 0
    for row in reader:
        countries.append(row[0])
        lats.append(float(row[1]))
        lons.append(float(row[2]))
        i = i + 1
    
m = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
              lat_0=0, lon_0=0)

m.drawcoastlines()
m.drawcountries()
#m.fillcontinents(color = 'gray')
m.drawmapboundary()
#m.drawmeridians(np.arange(0, 360, 30))
#m.drawparallels(np.arange(-90, 90, 30))

for country, lon, lat, in zip(countries, lons, lats):
    G.add_node(country)
    x,y = m(lon, lat)
    pos[country] = (x,y)
    #m.plot(x, y, 'yo', markersize=msize)
    
nx.draw_networkx(G,pos,node_size=50,node_color='yellow',labels = False)

#plt.show()