def plot_co_x(cox, start, end, size = (20,20), title = '', weighted=False, weight_threshold=10):

        """ Plotting function for keyword graphs

        Parameters
        --------------------
        cox: the coword networkx graph; assumes that nodes have attribute 'topic'
        start: start year
        end: end year
        """

        plt.figure(figsize=size)
        plt.title(title +' %s - %s'%(start,end), fontsize=18)
        if weighted:
            elarge=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] >weight_threshold]
            esmall=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] <=weight_threshold]
            pos=nx.graphviz_layout(cox) # positions for all nodes
            nx.draw_networkx_nodes(cox,pos,
                node_color= [s*4500 for s in nx.eigenvector_centrality(cox).values()],
                node_size = [s*6+20  for s in nx.degree(cox).values()],
                alpha=0.7)
            # edges
            nx.draw_networkx_edges(cox,pos,edgelist=elarge,
                                width=1, alpha=0.5, edge_color='black') #, edge_cmap=plt.cm.Blues
            nx.draw_networkx_edges(cox,pos,edgelist=esmall,
                                width=0.3,alpha=0.5,edge_color='yellow',style='dotted')
            # labels
            nx.draw_networkx_labels(cox,pos,font_size=10,font_family='sans-serif')
            plt.axis('off')
        else:
            nx.draw_graphviz(cox, with_labels=True,
                         alpha = 0.8, width=0.1,
                         fontsize=9,
                         node_color = [s*4 for s in nx.eigenvector_centrality(cox).values()],
                         node_size = [s*6+20 for s in nx.degree(cox).values()])
示例#2
0
 def displayGraph(self, g, label=False):
     axon, sd = axon_dendrites(g)
     sizes = node_sizes(g) * 50
     if len(sizes) == 0:
         print('Empty graph for cell. Make sure proto file has `*asymmetric` on top. I cannot handle symmetric compartmental connections')
         return
     weights = np.array([g.edge[e[0]][e[1]]['weight'] for e in g.edges()])
     pos = nx.graphviz_layout(g, prog='twopi')
     xmin, ymin, xmax, ymax = 1e9, 1e9, -1e9, -1e9
     for p in list(pos.values()):
         if xmin > p[0]:
             xmin = p[0]
         if xmax < p[0]:
             xmax = p[0]
         if ymin > p[1]:
             ymin = p[1]
         if ymax < p[1]:
             ymax = p[1]        
     edge_widths = 10.0 * weights / max(weights)
     node_colors = ['k' if x in axon else 'gray' for x in g.nodes()]
     lw = [1 if n.endswith('comp_1') else 0 for n in g.nodes()]
     self.axes.clear()
     try:
         nx.draw_graphviz(g, ax=self.axes, prog='twopi', node_color=node_colors, lw=lw)
     except (NameError, AttributeError) as e:
         nx.draw_spectral(g, ax=self.axes, node_color=node_colors, lw=lw, with_labels=False, )
def main():

    if len(sys.argv) < 2:
        sys.exit('Usage: %s $json_file' % sys.argv[0])

    if not os.path.exists(sys.argv[1]):
        sys.exit('ERROR: %s was not found!' % sys.argv[1])

    if len(sys.argv) == 2:
        G = merge_same_node(parse_saaf_json(sys.argv[1]))
        nx.draw_graphviz(G, prog='dot')
        plt.axis('off')
        plt.savefig("merged_by_networkx.png")
        json.dump(json_graph.node_link_data(G),
                  open('ford3js.json', 'w'),
                  sort_keys=True,
                  indent=4)
    if len(sys.argv) == 3:
        G1 = merge_same_node(parse_saaf_json(sys.argv[1]))
        G2 = merge_same_node(parse_saaf_json(sys.argv[2]))
        GM = isomorphism.DiGraphMatcher(G2, G1, node_match=op_match)
        #GM = isomorphism.DiGraphMatcher(G2, G1)
        print GM.is_isomorphic()
        print GM.subgraph_is_isomorphic()
        print GM.mapping
示例#4
0
def salva_grafoNX_imagem(G):
    """
    Salva grafos em formato png e dot
    """
    nx.draw_graphviz(G)
    nx.write_dot(G, 'relatorios/grafo_lei_vs_lei.dot')
    P.savefig('relatorios/grafo_lei_vs_lei.png')
示例#5
0
    def render_community_graph(self, show_single_nodes=True):
        added_nodes = set()
        graph = nx.Graph()
        for edge, _ in self.adjacency_matrix.iteritems():
            player_one = self.__players[edge.player_one]
            player_two = self.__players[edge.player_two]
            added = False
            if show_single_nodes:
                graph.add_node(edge.player_one)
                graph.add_node(edge.player_two)
                added = True
            if player_one.community == player_two.community:
                graph.add_edge(edge.player_one, edge.player_two)
                added = True
            if added:
                added_nodes.add(edge.player_one)
                added_nodes.add(edge.player_two)

        for node in self.nodes:
            if node.fide_id in added_nodes:
                graph.node[node.fide_id]['elo_rank'] = math.floor(node.elo/100) * 100

        min_val = self.__min_elo
        max_val = 2900
        elo_levels = range(min_val, max_val, 100)
        color_levels = np.linspace(1, 0, num=len(elo_levels), endpoint=True)
        color_value_map = {elo: color for (elo, color) in zip(elo_levels, color_levels)}
        color_values = [color_value_map.get(graph.node[n]['elo_rank'], 0.0) for n in graph.nodes()]

        nx.draw_graphviz(graph, cmap=pylab.get_cmap('jet'), node_color=color_values,
                         node_size=100)
def minimalColoring (probMatrix, contigs, cutoff = 0.01):
	# create a graph based on the probMatrix
	probG = nx.Graph()
	for i in range (len(contigs)):
		contigi = contigs[i]
		if contigi in excluded_utgs:
			print "yo"
			continue
		probG.add_node(contigi)
		for j in range (i+1, len(contigs)):
			contigj = contigs[j]
			if contigi in excluded_utgs:
				print "yo"
				continue
			if np.isnan(probMatrix[i][j]):
				continue
			if probMatrix[i][j] > cutoff:
				probG.add_edge(contigi, contigj)
	nx.draw_graphviz(probG)
	plt.savefig(out_tag + "_color_groups.png")
	plt.clf()	
	#print probG.nodes()
	#print probG.edges()
	#print nx.find_cliques(probG)
	components = list(nx.connected_components(probG))
	#components = list(nx.find_cliques(probG))
	return components
def main():

    if len(sys.argv) < 2:
        sys.exit('Usage: %s $json_file' % sys.argv[0])

    if not os.path.exists(sys.argv[1]):
        sys.exit('ERROR: %s was not found!' % sys.argv[1])

    if len(sys.argv) == 2:
        G = merge_same_node(parse_saaf_json(sys.argv[1]))
        nx.draw_graphviz(G, prog = 'dot')
        plt.axis('off')
        plt.savefig("merged_by_networkx.png")
        json.dump(
            json_graph.node_link_data(G),
            open('ford3js.json', 'w'),
            sort_keys = True,
            indent = 4
        )
    if len(sys.argv) == 3:
        G1 = merge_same_node(parse_saaf_json(sys.argv[1]))
        G2 = merge_same_node(parse_saaf_json(sys.argv[2]))
        GM = isomorphism.DiGraphMatcher(G2, G1, node_match = op_match)
        #GM = isomorphism.DiGraphMatcher(G2, G1)
        print GM.is_isomorphic()
        print GM.subgraph_is_isomorphic()
        print GM.mapping
示例#8
0
    def render_graph(self, max_edges=None, min_games=1):
        added_nodes = set()
        graph = nx.Graph()
        for i, (edge, num) in enumerate(self.adjacency_matrix.iteritems()):
            if max_edges and i > max_edges:
                break
            if num < min_games:
                continue
            graph.add_edge(edge.player_one, edge.player_two)
            added_nodes.add(edge.player_one)
            added_nodes.add(edge.player_two)

        for node in self.nodes:
            if node.fide_id in added_nodes:
                graph.node[node.fide_id]['elo_rank'] = int(math.floor(node.elo/100) * 100)

        min_val = self.__min_elo
        max_val = 2900
        elo_levels = range(min_val, max_val, 100)
        color_levels = np.linspace(1, 0, num=len(elo_levels), endpoint=True)
        color_value_map = {elo: color for (elo, color) in zip(elo_levels, color_levels)}
        color_values = [color_value_map.get(graph.node[n]['elo_rank'], 0.0) for n in graph.nodes()]

        nx.draw_graphviz(graph, cmap=pylab.get_cmap('jet'), node_color=color_values,
                         node_size=100)
示例#9
0
 def displayGraph(self, g, label=False):
     axon, sd = axon_dendrites(g)
     sizes = node_sizes(g) * 50
     if len(sizes) == 0:
         print(
             'Empty graph for cell. Make sure proto file has `*asymmetric` on top. I cannot handle symmetric compartmental connections'
         )
         return
     node_colors = ['k' if x in axon else 'gray' for x in g.nodes()]
     lw = [1 if n.endswith('comp_1') else 0 for n in g.nodes()]
     self.axes.clear()
     try:
         nx.draw_graphviz(g,
                          ax=self.axes,
                          prog='twopi',
                          node_color=node_colors,
                          lw=lw)
     except (NameError, AttributeError) as e:
         nx.draw_spectral(
             g,
             ax=self.axes,
             node_color=node_colors,
             lw=lw,
             with_labels=False,
         )
示例#10
0
def draw_all(filename='out.png'):
  """
  draw every graph connected and everything yeah
  """
  def _make_abbreviation(string):
    s = string.split(" ")
    return ''.join([word[0] for word in s])
  import matplotlib.pyplot as plt
  plt.clf()
  this = sys.modules[__name__]
  relationals = [getattr(this, i) for i in this.__dict__ if isinstance(getattr(this,i), Relational)]
  biggraph = nx.DiGraph()
  for r in relationals:
    for n in r._nk.nodes():
      biggraph.add_edges_from(n._nk.edges())
  for n in biggraph.nodes():
    if n.external_parents:
      for p in n.external_parents:
        biggraph.add_edges_from(p._nk.edges())
    if n.external_childs:
      for c in n.external_childs:
        biggraph.add_edges_from(c._nk.edges())
  for n in biggraph.nodes():
    if "." not in n.name:
      n.name = n.name+"."+_make_abbreviation(n.container.name)
  nx.draw_graphviz(biggraph,prog='neato',width=1,node_size=300,font_size=4,overlap='scalexy')
  plt.savefig(filename)
def minimalColoring(probMatrix, contigs, cutoff=0.01):
    # create a graph based on the probMatrix
    probG = nx.Graph()
    for i in range(len(contigs)):
        contigi = contigs[i]
        if contigi in excluded_utgs:
            print "yo"
            continue
        probG.add_node(contigi)
        for j in range(i + 1, len(contigs)):
            contigj = contigs[j]
            if contigi in excluded_utgs:
                print "yo"
                continue
            if np.isnan(probMatrix[i][j]):
                continue
            if probMatrix[i][j] > cutoff:
                probG.add_edge(contigi, contigj)
    nx.draw_graphviz(probG)
    plt.savefig(out_tag + "_color_groups.png")
    plt.clf()
    #print probG.nodes()
    #print probG.edges()
    #print nx.find_cliques(probG)
    components = list(nx.connected_components(probG))
    #components = list(nx.find_cliques(probG))
    return components
def graph_draw(graph, with_labels=False, factor=1):
    nx.draw_graphviz(graph,
                     node_size=[(factor * 16 * graph.degree(n))
                                for n in graph],
                     node_color=[graph.depth[n] for n in graph],
                     with_labels=with_labels)
    matplotlib.pyplot.show()
示例#13
0
    def render_graph(self, max_edges=None, min_games=1):
        added_nodes = set()
        graph = nx.Graph()
        for i, (edge, num) in enumerate(self.adjacency_matrix.iteritems()):
            if max_edges and i > max_edges:
                break
            if num < min_games:
                continue
            graph.add_edge(edge.player_one, edge.player_two)
            added_nodes.add(edge.player_one)
            added_nodes.add(edge.player_two)

        for node in self.nodes:
            if node.fide_id in added_nodes:
                graph.node[node.fide_id]['elo_rank'] = int(
                    math.floor(node.elo / 100) * 100)

        min_val = self.__min_elo
        max_val = 2900
        elo_levels = range(min_val, max_val, 100)
        color_levels = np.linspace(1, 0, num=len(elo_levels), endpoint=True)
        color_value_map = {
            elo: color
            for (elo, color) in zip(elo_levels, color_levels)
        }
        color_values = [
            color_value_map.get(graph.node[n]['elo_rank'], 0.0)
            for n in graph.nodes()
        ]

        nx.draw_graphviz(graph,
                         cmap=pylab.get_cmap('jet'),
                         node_color=color_values,
                         node_size=100)
示例#14
0
def map_flows(catalog):
    import analysis as trans
    fm = trans.FlowMapper()

    read_exceptions = {}
    for i,fn in enumerate(os.listdir('.\\repository_data\\')):
        print i, fn
        try:
            sys = catalog.read(''.join(['.\\repository_data\\',fn]))
        except Exception as e:
            read_exceptions[fn] = e
            print '\t',e.message
        fm.add_system(sys)
        if i > 5:
            break

    graph = fm.transformation_graph()
    fm.stats()
    nx.draw_graphviz(graph,prog='dot',root='energy')
    print nx.to_numpy_matrix(graph) > 0
#    pdg = nx.to_pydot(graph)
#    pdg.write_png('transform.png')
#    nx.graphviz_layout(graph,prog='neato')
#    nx.draw_graphviz(graph)
    plt.show()
示例#15
0
def plot_graph(graph=None, path=None, dist=None, best=None, best_dist=None,
			   save=False, name=None, title=None):
	"""
	Plot a TSP graph.

	Parameters
	----------
	graph: An XML TSP graph. If None, use the default graph from parse_xml_graph.
	path: An ordered list of node indices. If given, plot the path. Otherwise, plot
		the underlying graph.
	dist: Distances of the paths in path.
	best: Empirical best path.
	best_dist: Empirical best path distance.
	save: If True, saves the graph as name.png. Otherwise, draws the graph.
	name: Graph is saved as name.png
	title: Caption of the graph.
	"""
	# Check input parameters 
	if save:
		assert (name is not None), 'If saving graph, must provide name'

	# Initialize graph
	if graph is not None:
		g = parse_xml_graph(graph)
	else:
		g = parse_xml_graph()
	G = nx.from_numpy_matrix(g)

	# Plot path, if applicable
	edges = list()
	edge_colors = list()
	if path is not None:
		edges.extend([(path[i], path[i+1]) for i in range(len(path)-1)])
		edges.append((path[-1], path[0]))
		edge_colors.extend(['r' for i in range(len(path))])
	if best is not None:
		edges.extend([(best[i], best[i+1]) for i in range(len(best)-1)])
		edges.append((best[-1], best[0]))
		edge_colors.extend(['b' for i in range(len(best))])
	if path is None and best is None:
		edges = G.edges()

	plt.clf()
	fig = plt.figure(figsize=(14, 5.5))
	ax1 = fig.add_subplot(121)
	ax2 = fig.add_subplot(122)
	nx.draw_graphviz(G, edgelist=edges, edge_color=edge_colors, with_labels=None,
		node_color='k', node_size=100, ax=ax1)
	ax1.set_title(title)
	ax2.plot(np.arange(1, len(dist)+1), dist, color='r', alpha=0.9, label='Best found path')
	ax2.hlines(best_dist, 0, len(dist)+1, color='b', label='Best path')
	ax2.set_xlim(1, max(len(dist), 2));
	ax2.legend()

	if not save:
		plt.show()
	else:
		plt.savefig('temp/{}.png'.format(name))
	fig.clf()
示例#16
0
文件: overlayviz.py 项目: loox-/p2ner
    def drawPlot(self):
        a = nx.to_agraph(self.g)
        self.g = nx.from_agraph(a)
        self.fig = pylab.figure()
        nx.draw_graphviz(self.g, prog='neato')
        plt.savefig("path.png")

        self.image.set_from_file("path.png")
示例#17
0
 def plot_graph(graph):
     """
     \brief Produce de graphviz file related to a DBGraph and show the graph
     \param graph A DBGraph instance
     """
     import matplotlib.pyplot  as plt
     draw_graphviz(graph)
     plt.show()
示例#18
0
def debug_graph( graph, message="" ):
    import matplotlib.pyplot as plt
    print message

    pos = nx.layout.fruchterman_reingold_layout( graph )
    nx.draw( graph, pos )
    nx.draw_graphviz( graph )
    plt.show()
示例#19
0
def graph_draw(graph):
    nx.draw_graphviz(
        graph,
        node_size=[16 * graph.degree(n) for n in graph],
        node_color=[graph.depth[n] for n in graph],
        with_labels=False,
    )
    matplotlib.pyplot.show()
示例#20
0
def s_draw(listdata):
    '''Draw the weighted graph associated with the Seifert data 'listdata'.'''
    startree = make_graph(listdata)
    labels = dict((n, '%s,%s' %(n,a['weight'])) for n,a in 
                  startree.nodes(data=True))
    nx.draw_graphviz(startree, labels=labels, node_size=700, width=3, 
                     alpha=0.7)    
    plt.show()    
示例#21
0
 def update_graph(self):
     '''Redraw graph in matplotlib.pyplot.'''
     plt.clf() # erase figure
     labels = dict((n, '%s,%s' %(n,a['weight'])) \
                   for n,a in self.graph.nodes(data=True))
     nx.draw_graphviz(self.graph, labels=labels, node_size=700, width=3, 
                      alpha=0.7)
     plt.show()
def draw_neighbor(G,compound):
	tmp = nx.all_neighbors(G,compound)
	Gpart = nx.Graph()
	for x in tmp:
		Gpart.add_edge(x,compound,color=G.edge[x][compound]['color'])
	nx.draw(Gpart)
        plt.savefig("path_test.png")
        nx.draw_graphviz(Gpart)
        nx.write_dot(Gpart,'file_test.dot')
示例#23
0
 def test_lobster(self):
     import networkx as nx
     import matplotlib.pyplot as plt
     #g = nx.random_lobster(15, 0.8, 0.1)
     g = nx.barbell_graph(7, 5)
     #g = nx.erdos_renyi_graph(15, 0.2)
     nx.draw_graphviz(g)
     plt.savefig("/tmp/lobster.png")
     print distancematrix.matrix_calls(g.edges(), 7)
示例#24
0
def printGraph(G, gname):
  h = networkx.DiGraph()
  h.add_edges_from( G.edges() )
  networkx.draw_graphviz(h)
  fname = os.path.sep.join([config.Config.imgCacheDir, 'graph_%s.png'%(gname) ] )
  plt.savefig(fname)
  plt.clf()
  fname = os.path.sep.join([config.Config.cacheDir, 'graph_%s.gexf'%(gname) ] )
  networkx.readwrite.gexf.write_gexf( h, fname)
示例#25
0
文件: ffnetlib.py 项目: xaviet/toe
def test():
    from ffnet import mlgraph, ffnet
    import networkx as NX
    import pylab
    conec1 = mlgraph((2, 2, 2), biases=False)
    net1 = ffnet(conec1)
    conec2 = mlgraph((4, 2, 2, 1), biases=True)
    net2 = ffnet(conec2)
    NX.draw_graphviz(net1.graph, prog='dot')
    pylab.show()
示例#26
0
def printGraph(G, gname):
    h = networkx.DiGraph()
    h.add_edges_from(G.edges())
    networkx.draw_graphviz(h)
    fname = os.path.sep.join([config.imgCacheDir, 'graph_%s.png' % gname])
    plt.savefig(fname)
    plt.clf()
    fname = os.path.sep.join([config.cacheDir, 'graph_%s.gexf' % gname])
    networkx.readwrite.gexf.write_gexf(h, fname)
    return
示例#27
0
def PlotNetwork(G,OutputFile="Graph.dot"):
    """Plot a graph to screen and also save output."""

    try:
        networkx.draw_graphviz(G)
    except:
        logger.error("could not plot graph to screen.  Check X / Matplotlib settings.")
        
    networkx.write_dot(G, OutputFile)
    logger.info("Wrote: %s", OutputFile)
def drawTaxonomyGraph(taxonomy):

    G=nx.DiGraph()
    for child in taxonomy:
        for parent in taxonomy[child]:
            G.add_edge(parent, child, {'weight': 1})
    graphviz_pos = nx.graphviz_layout(G, prog="dot")
    nx.draw_graphviz(G, with_labels=False, node_size=10, font_size = 7, edge_color='g')
    nx.draw_networkx_labels(G, pos = graphviz_pos, font_size = 7)
    plt.savefig("taxonomy.png")
示例#29
0
def PlotNetwork(G,OutputFile="Graph.dot"):
    """Plot a graph to screen and also save output."""

    try:
        networkx.draw_graphviz(G)
    except:
        logger.error("could not plot graph to screen.  Check X / Matplotlib settings.")
        
    networkx.write_dot(G, OutputFile)
    logger.info("Wrote: %s", OutputFile)
示例#30
0
文件: yatot.py 项目: imclab/yatot
 def drawGraph(self):
     lbls = {}
     for node in self._graph.nodes():
         lbls[node] = self._graph.node[node]["nName"]
     nx.draw_graphviz(self._graph, prog = "twopi",       \
                      with_labels = True, labels = lbls)
     path = "{0}.png".format(len(self._hints))
     plt.savefig(path)
     plt.show()      
     return path
def transferConditions(dag, l, maxCount=2):
	"""
	Return a color (for quality of transfer) and a list
	of SynonymsList"""
	count = 0
	
	lSet = set()
	terms_to_remove = set()
	
	for term in l:
		lSet.add(getSynList(dag, term))
	
	# Colored graph
	for e in lSet:
		dag.node[e]["color"] = "blue"
	
	for synList in lSet:
		if synList is None:
			return "RED", "Error"
		
	for start in lSet:
		for a, b in nx.bfs_edges(dag, start, reverse=True):
			if b in lSet:
				terms_to_remove.add(b)
	
	for e in terms_to_remove:
		if e in lSet:
			lSet.remove(e)
	
	if len(lSet) == 1:
		finalSynList = list(lSet)[0]
		
		# Draw
		dag.node[finalSynList]["fontcolor"] = "green"
		nx.draw_graphviz(dag)
		nx.write_dot(dag, "output2.dot")
		os.popen("dot -Tpng output2.dot > output2.png")
		
		return "GREEN", list(lSet)
	
	else:
		fca = firstCommonAncestors(dag, lSet)
		
		for e in fca:
			dag.node[e]["fontcolor"] = "orange"
	
		# Draw
		nx.draw_graphviz(dag)
		nx.write_dot(dag, "output2.dot")
		os.popen("dot -Tpng output2.dot > output2.png")
		
		if count <= maxCount:
			return "ORANGE", fca
		else:
			return "RED", "Error"
示例#32
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')
示例#33
0
    def draw_and_save_grapgh(self):
        
        self.create_network()
        print '\n\n** Saving graphs in {0} **'.format(self.stat_dir)
        plt.figure(0)
        plt.subplot(311)
        plt.title('Possible interaction')
        fig = nx.draw_graphviz(self.graph_low \
                , prog='twopi' \
                , node_size= 80 \
                , font_size = 6  \
                , with_labels = True \
                , width = 0.5 \
                , node_color = 'yellow' \
                )
        
        plt.subplot(312)
        plt.title('Possible copies')
        nx.draw_graphviz(self.graph_med \
                , prog='fdp' \
                , node_size= 80 \
                , font_size = 6 \
                , with_labels = True \
                , width = 1.0 \
                , node_color = 'yellow' \
                )
        
        plt.subplot(313)
        plt.title('Definite copies')
        nx.draw_graphviz(self.graph_high \
                , prog='fdp' \
                , node_size= 80 \
                , font_size = 6 \
                , with_labels = True \
                , width = 1.9 \
                , node_color = 'yellow' \
                )
        plt.savefig(self.stat_dir+'/assignment.png')


        plt.figure(1)
        plt.title('Possible interactions')
        fig = nx.draw_graphviz(self.graph_low, prog='twopi')
        plt.savefig(self.stat_dir+'/low.png')
        
        plt.figure(2)
        plt.title('Possible copies')
        nx.draw_graphviz(self.graph_med, prog='twopi')
        plt.savefig(self.stat_dir+'/medium.png')
        
        plt.figure(3)
        plt.title('Definite copies')
        nx.draw_graphviz(self.graph_high, prog='twopi')
        plt.savefig(self.stat_dir+'/high.png')
示例#34
0
def demo_write_doc():
    """demo_write_doc"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    nx.draw_graphviz(g)
    nx.write_dot(g, 'g.dot')
    def show(self):
        graph = nx.DiGraph()

        for n in self.nodes():
            graph.add_node(n)

        for n_i, n_j in self.edges():
            graph.add_edge(n_i, n_j)
        
        nx.draw_graphviz(graph)
        plt.show()
  def draw_digraph(self):
    print("Draw DiGraph")
    
    self.load_market()
    
    self.df_markets['cur1_account'] = self.df_markets['market']+'_'+self.df_markets['cur1']
    self.df_markets['cur2_account'] = self.df_markets['market']+'_'+self.df_markets['cur2']
    
    print(self.df_markets)

    set_cur1 = sets.Set(self.df_markets['cur1'].unique())
    set_cur2 = sets.Set(self.df_markets['cur2'].unique())
    currencies = set_cur1.union(set_cur2)
    print(currencies)
    
    set_acc_cur1 = sets.Set(self.df_markets['cur1_account'].unique())
    set_acc_cur2 = sets.Set(self.df_markets['cur2_account'].unique())
    accounts = set_acc_cur1.union(set_acc_cur2)
    
    #print(accounts)
    
    G = nx.DiGraph()
    G.add_nodes_from(currencies)
    G.add_nodes_from(accounts)


    for i in self.df_markets.index:
      market = self.df_markets['market'][i]
      cur1 = self.df_markets['cur1'][i]
      cur2 = self.df_markets['cur2'][i]
      cur1_account = self.df_markets['cur1_account'][i]
      cur2_account = self.df_markets['cur2_account'][i]
      active = self.df_markets['active'][i]
      fullmarketname = self.df_markets['fullmarketname'][i]
      #print("{fullmarketname}".format(fullmarketname=fullmarketname))
      G.add_edge(cur1_account, cur2_account) # label=market #, label='0'
      G.add_edge(cur2_account, cur1_account)
      
      G.add_edge(cur1_account, cur1)
      G.add_edge(cur1, cur1_account)

      G.add_edge(cur2_account, cur2)
      G.add_edge(cur2, cur2_account)


    #nx.draw(G)
    #nx.draw_random(G)
    #nx.draw_circular(G)
    #nx.draw_spectral(G)
    #plt.savefig("path.png")    
    #plt.show()

    nx.draw_graphviz(G)
    nx.write_dot(G,'path.dot')
示例#37
0
def display_graph(similarity, languages):
    # display network of languages

    num_lang = len(languages)
    offset = 0.07
    dt = [('len', float)]
    similarity = similarity.view(dt)

    G = nx.from_numpy_matrix(similarity)
    G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())), languages)))
    nx.draw_graphviz(G, prog='neato', alpha=0.5, with_labels=True)
    plt.show()
示例#38
0
def display_graph(similarity, languages):
		# display network of languages

		num_lang = len(languages)
		offset=0.07
		dt = [('len',float)]
		similarity = similarity.view(dt)

		G = nx.from_numpy_matrix(similarity)
		G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),languages)))
		nx.draw_graphviz(G,prog='neato',alpha=0.5,with_labels=True)
		plt.show()
def disallowedEdges (probMatrix, contigs, cutoff = 0.001):
	badGraph = nx.Graph()
	for i in range(len(contigs)):
		contigi = contigs[i]
		for j in range (i+1, len(contigs)):
			contigj = contigs[j]
			if probMatrix[i][j] <= cutoff:
				badGraph.add_edge(contigi, contigj)
	nx.draw_graphviz(badGraph)
	plt.savefig(out_tag + "_disallowededges.png")
	plt.clf()	
	return badGraph
def disallowedEdges(probMatrix, contigs, cutoff=0.001):
    badGraph = nx.Graph()
    for i in range(len(contigs)):
        contigi = contigs[i]
        for j in range(i + 1, len(contigs)):
            contigj = contigs[j]
            if probMatrix[i][j] <= cutoff:
                badGraph.add_edge(contigi, contigj)
    nx.draw_graphviz(badGraph)
    plt.savefig(out_tag + "_disallowededges.png")
    plt.clf()
    return badGraph
示例#41
0
def plot_networkx_graph(graph, show=True):
    plt.figure()
    objs, labels, colors = zip(*[(d[0], d[1]['label'], d[1]['color'])
                                 for d in graph.nodes_iter(data=True)])
    nx.draw_graphviz(graph,
                     font_size=10,
                     iteration=200,
                     node_color=colors,
                     scale=1,
                     labels=dict(zip(objs, labels)))
    if show:
        plt.show()
示例#42
0
    def display(self, graph: nx.Graph = None):
        online = False
        if graph == None:
            online = True
            graph = self
        plt.title('discovery')  # hard code the title
        nx.draw_graphviz(graph)  # expand using spectral layout
        #nx.draw_networkx_edge_labels(graph, pos=nx.spectral_layout(self))  # draw labels
        #nx.draw_networkx_nodes(graph, pos=nx.graphviz_layout(self), nodelist=[self.head], node_color='g')

        if online:
            self.head.fullGraph.fig.canvas.draw()
        plt.show(block=False)  # show non blocking
示例#43
0
    def draw_landscape(self):
        for config in range(2**self.number_genes):
            self.landscape.add_node(bin(config))
        for config in range(2**self.number_genes):
            self.set_configuration(config)
            next_config = self.change_state()
            next_config.reverse()
            bla = [str(x) for x in next_config]
            bina = '0b' + ''.join(bla)
            self.landscape.add_edge(bin(config), bina)

        nx.draw_graphviz(self.landscape)
        plt.show()
示例#44
0
文件: gui.py 项目: BhallaLab/moose
 def displayGraph(self, g, label=False):
     axon, sd = axon_dendrites(g)
     sizes = node_sizes(g) * 50
     if len(sizes) == 0:
         print('Empty graph for cell. Make sure proto file has `*asymmetric` on top. I cannot handle symmetric compartmental connections')
         return
     node_colors = ['k' if x in axon else 'gray' for x in g.nodes()]
     lw = [1 if n.endswith('comp_1') else 0 for n in g.nodes()]
     self.axes.clear()
     try:
         nx.draw_graphviz(g, ax=self.axes, prog='twopi', node_color=node_colors, lw=lw)
     except (NameError, AttributeError) as e:
         nx.draw_spectral(g, ax=self.axes, node_color=node_colors, lw=lw, with_labels=False, )
示例#45
0
def draw_network_load(topology, result, filename, plotdir):
    """Draw topology with node colors according to stack and node size and link
    color according to server/cache hits and link loads.

    Nodes are colored according to COLORMAP. Edge are colored on a blue-red
    scale where blue means min link load and red means max link load.
    Sources and caches have variable size proportional to their hit ratios.

    Parameters
    ----------
    topology : Topology
        The topology to draw
    result : Tree
        The tree representing the specific experiment result from which metric
        are read
    plotdir : string
        The directory onto which draw plots
    filename : string
        The name of the image file to save
    """
    stack = stack_map(topology)
    node_color = [COLORMAP[stack[v]] for v in topology.nodes_iter()]
    node_min = 50
    node_max = 600
    hits = result["CACHE_HIT_RATIO"]["PER_NODE_CACHE_HIT_RATIO"].copy()
    hits.update(result["CACHE_HIT_RATIO"]["PER_NODE_SERVER_HIT_RATIO"])
    hits = np.array(
        [hits[v] if v in hits else 0 for v in topology.nodes_iter()])
    min_hits = np.min(hits)
    max_hits = np.max(hits)
    hits = node_min + (node_max - node_min) * (hits - min_hits) / (max_hits -
                                                                   min_hits)
    link_load = result["LINK_LOAD"]["PER_LINK_INTERNAL"].copy()
    link_load.update(result["LINK_LOAD"]["PER_LINK_EXTERNAL"])
    link_load = [
        link_load[e] if e in link_load else 0 for e in topology.edges()
    ]
    plt.figure()
    nx.draw_graphviz(
        topology,
        node_color=node_color,
        node_size=hits,
        width=2.0,
        edge_color=link_load,
        edge_cmap=mpl.colors.LinearSegmentedColormap.from_list(
            "bluered", ["blue", "red"]),
        with_labels=False,
    )
    plt.savefig(os.path.join(plotdir, filename), bbox_inches="tight")
示例#46
0
def draw_neighbor(G, compound):
    tmp = G.neighbors(str(compound))
    Gpart = nx.Graph()
    print tmp
    for x in tmp:
        # print x
        print G.edge[x][compound]["weight"]
        Gpart.add_edge(x, compound, color=G.edge[x][compound]["color"], weight=G.edge[x][compound]["weight"])
    nx.draw(Gpart)
    name = "path_%s.png" % str(compound)
    plt.savefig(name)

    nx.draw_graphviz(Gpart)
    name1 = "file_%s.dot" % str(compound)
    nx.write_dot(Gpart, name1)
示例#47
0
文件: mrf.py 项目: acompa/mrf
def visualize_rooted_tree(t, prog='dot'):
    '''
    Visualize tree graph using graphviz dot.

    Parameters
    ----------
    t : networkx.DiGraph
        The tree to visualize.
    Returns
    -------
    None
    '''

    nx.draw_graphviz(t, prog=prog, font_size=6, node_shape='s',
            edge_color='gray', node_size=500, node_color='c')
def create_graphviz_files(inm, tps, path):
    """Write master data to .dot file for use in GVEdit
  
  Args:
    inm (Graph): Graph structure to be written to file
    tps (Graph): Graph structure to be written to file
    path (String): Path to save the created .dot files

  Returns:
    float: Void
  """
    nx.draw_graphviz(inm)
    nx.write(inm, path + "inm/inm.dot")
    nx.draw_graphviz(tps)
    nx.write(tps, path + "tps/tps.dot")
示例#49
0
文件: seminfg.py 项目: chakwing/PyNFG
    def draw_graph(self, subgraph=None):
        """Draw the DAG representing the topology of the SemiNFG.

        :arg subgraph: (Optional) node names of subset of nodes to include in
           drawing. Default is self.nodes. If not specified, all nodes are
           graphed.
        :type subgraph: set or list

        .. note::

           This method uses the :py:mod:`matplotlib.pyplot` and
           :py:mod:`networkx` packages.

        """
        G = nx.DiGraph()
        if not subgraph:
            nodelist = self.node_dict.values()
        else:
            nodelist = []
            for name in subgraph:
                nodelist.append(self.node_dict[name])
        nodeset = set(nodelist)
        for n in nodeset:
            for child in nodeset.intersection(self.edges[n.name]):
                G.add_edge(n.name, child.name)
        pos = nx.spring_layout(G, iterations=100)
        #       nx.draw_networkx(G, pos)
        fig = nx.draw_graphviz(G, prog='dot')
        plt.show()
        return fig
示例#50
0
    def drawTableGraph(self, DG=None, outputFnamePrefix=None):
        """
		"""
        sys.stderr.write(
            "Drawing the reference graph of all tables in the graph ...\n")

        import pylab, numpy
        import matplotlib as mpl
        counter = 0
        for unDirectedSubG in nx.connected_component_subgraphs(
                DG.to_undirected()):
            #connected_component_subgraphs() can't work on directed graph.
            #nx.draw_circular(DG,with_labels=False, alpha=0.5)
            pylab.clf()
            #get rid of all cushion around the figure
            axe_pvalue = pylab.axes(
                [0, 0, 1.0, 1.0],
                frameon=False)  #left gap, bottom gap, width, height
            pylab.figure(axe_pvalue.figure.number)

            #pylab.axis("off")
            #pylab.figure(figsize=(100, 60))
            layout = 'dot'
            """
			pos = nx.graphviz_layout(DG, prog=layout)
			nx.draw_networkx_edges(DG, pos, alpha=0.9, width=0.8)
			
			nx.draw_networkx_nodes(DG, pos, alpha=0.9, width=0, linewidths=0.5, cmap=mpl.cm.jet, vmin=0, vmax=1.0)
			"""
            subG = DG.subgraph(unDirectedSubG.nodes())
            #check toplogical sortable
            sys.stderr.write("is component %s a DAG? %s.\n" %
                             (counter, nx.is_directed_acyclic_graph(subG)))

            nx.draw_graphviz(subG,
                             prog=layout,
                             with_labels=True,
                             node_size=10,
                             font_size=1,
                             width=0.2,
                             linewidths=0.2,
                             alpha=0.5)
            pylab.savefig('%s_graphviz_%s_component_%s.png' %
                          (outputFnamePrefix, layout, counter),
                          dpi=700)
            counter += 1
        sys.stderr.write(".\n")
示例#51
0
def draw_stack_deployment(topology, filename, plotdir):
    """Draw a topology with different node colors according to stack

    Parameters
    ----------
    topology : Topology
        The topology to draw
    plotdir : string
        The directory onto which draw plots
    filename : string
        The name of the image file to save
    """
    stack = stack_map(topology)
    node_color = [COLORMAP[stack[v]] for v in topology.nodes_iter()]
    plt.figure()
    nx.draw_graphviz(topology, node_color=node_color, with_labels=False)
    plt.savefig(os.path.join(plotdir, filename), bbox_inches="tight")
示例#52
0
 def draw_graph(self, docName):
     examples = inspec_data_reader()
     docText = [text for filename, text, gold_labels in examples if filename == docName][0]
     words = self.tokenize(docText) # Note: tuples if using a synFilter
     cooccurrence_dict, G = self.create_graph(words)
     G = G.to_undirected()
     labels = nx.draw_graphviz(G, with_labels=True, edge_color='0.5', width=0.5, font_color='blue', node_color='0.5', node_size=800)
     plt.show() 
示例#53
0
def drawGraph(sg):
    protSet = set()
    for ind, node in enumerate(sg.nodes()):
	if node.startswith("R_"):
            protSet.add(ind)
    
    sizes = []
    colors = []
    for i in xrange(0,len(sg)):
	if i in protSet:
            sizes.append(200)
            colors.append('r')
	else:
            sizes.append(50)
            colors.append('b')

    nx.draw_graphviz(sg, node_size = sizes, with_labels = False, node_color = colors)
示例#54
0
def centrality_drawGraph(G, CentralMeasure):

    color_values = [CentralMeasure[node] for node in G.nodes()]
    size_values = [1000 * CentralMeasure[node] + 100 for node in G.nodes()]

    nx.draw_graphviz(G,
                     cmap=plt.get_cmap('Blues'),
                     node_color=color_values,
                     vmin=0.0,
                     vmax=1.0,
                     edge_color='b',
                     with_labels=True,
                     node_size=size_values)

    ##nx.draw( G , """pos=nx.circular_layout(G), """ cmap = plt.get_cmap('YlGn') , node_color=values ,
    ##		 vmin = 0.0 , vmax = 1.0 , edge_color='b', with_labels = True , node_size=[v * 10000 for v in d.values()] )

    plt.show()
示例#55
0
    def draw(self):
        r""" Draw the system

            Draw the system with graphviz.

            Examples
            --------
            >>> import pylab as p
            >>> motor = Component('M', 1e-4, 3e-2)
            >>> powers = [Component('P{}'.format(i), 1e-6, 2e-4) for i in (0,1)]
            >>> S = System()
            >>> S['E'] = [powers[0], powers[1]]
            >>> S[powers[0]] = S[powers[1]] = [motor]
            >>> S[motor] = 'S'
            >>> S.draw()
            >>> p.show()

        """
        nx.draw_graphviz(self._graph)