Example #1
0
def getSvgForGraphPair(before, after, leftToRight=False):
    g1 = before.copy()
    g2 = after.copy()

    appendTag(g1)
    appendTag(g2)

    for n in g2:
        if 'tag' in g2.nodes[n] and n in g1:
            if g1.nodes[n].get('tag', None) != g2.nodes[n].get('tag'):
                g2.nodes[n]['fontcolor'] = 'red'

    edgesDeleted = [e for e in g1.edges if e not in g2.edges]
    nodesDeleted = [n for n in g1.nodes if n not in g2.nodes]
    edgesAdded = [e for e in g2.edges if e not in g1.edges]
    nodesAdded = [n for n in g2.nodes if n not in g1.nodes]

    for n in nodesDeleted:
        g1.nodes[n]['color'] = 'red'
        g1.nodes[n]['fontcolor'] = 'red'
        g2.add_node(n, color="white", label="")
    for n in nodesAdded:
        g2.nodes[n]['color'] = 'green'
        g2.nodes[n]['fontcolor'] = 'green'
        g1.add_node(n, color="white", label="")

    for (s, t) in edgesDeleted:
        g1.edges[s, t]['color'] = 'red'
        g1.edges[s, t]['fontcolor'] = 'red'
        g2.add_edge(s, t, color="white")

    for (s, t) in edgesAdded:
        g2.edges[s, t]['color'] = 'green'
        g2.edges[s, t]['fontcolor'] = 'green'
        g1.add_edge(s, t, color="white")

    if leftToRight:
        (_, _, x1, y1) = position(g1)
        transferPositions(g1, g2)
        (_, _, x2, y2) = position(g2)
    else:
        (_, _, x2, y2) = position(g2)
        transferPositions(g2, g1)
        (_, _, x1, y1) = position(g1)

    # Graphviz uses 96 DPI by default
    desiredX = max(x1, x2) / 96.0
    desiredY = max(y1, y2) / 96.0

    sizeAttr = "{},{}!".format(desiredX, desiredY)

    ag1 = to_agraph(g1)
    ag1.graph_attr['size'] = sizeAttr
    s1 = ag1.draw(format="svg", prog="neato")

    ag2 = to_agraph(g2)
    ag2.graph_attr['size'] = sizeAttr
    s2 = ag2.draw(format="svg", prog="neato")

    return (s1.decode("utf-8"), s2.decode("utf-8"))
Example #2
0
def draw(g, path=None):
    """
    Draw the graph g and return as png. The graph is plotted inline in an IPython notebook.
    When a path is given, also save the image to a file at path, using the export function.
    """
    if path is not None:
        to_agraph(G).draw(format='png', prog='dot', path=path)
    return Image(to_agraph(G).draw(format='png', prog='dot'))
Example #3
0
def static_graph(rules_dag):
    from networkx.drawing.nx_agraph import to_agraph

    graph = to_agraph(rules_dag)
    graph.node_attr['fontname'] = 'Arial, sans-serf'
    graph.edge_attr['fontname'] = 'Arial, sans-serf'

    with NamedTemporaryFile(suffix='.dot') as dot_file:
        graph.write(dot_file.name)

    graph.clear()

    with NamedTemporaryFile(mode='r', suffix='.svg') as temp_file:
        system(f'dot -Tsvg {dot_file.name} -o {temp_file.name}')

        # with open(temp_file.name) as f:
        svg = temp_file.read()
        insert_after = 'xmlns:xlink="http://www.w3.org/1999/xlink">'
        processed = svg.replace(insert_after, insert_after + """
            <style>
            a:hover polygon {
                fill: red;
            }
            </style>
        """)

    return processed
Example #4
0
def draw_graph(Pline,Qline,Vbus,phibus,filename='graph.png'):
    G = nx.DiGraph()
    ppc=case14.case14() 
    cols=['green']

    for bus in ppc['bus']:
        busnum=int(bus[0])
        phi=phibus[busnum-1]*180.0/numpy.pi
        xlabel='V:'+str('%.2f'%round(Vbus[busnum-1],2))+'kV /_'+str("%.2f" % round(phi,2))
        G.add_node(busnum,color=cols[0],label=busnum,xlabel=xlabel)
    for i,line in enumerate(ppc['branch']):
        ptag=''
        if numpy.isnan(Pline[i]):
            ptag='NA'
        else:
            ptag=str('%.2f'%round(Pline[i]*100,2))
            qtag=str('%.2f'%round(numpy.abs(Qline[i])*100,2))
            if Qline[i]<0:
                label='Pline:'+ptag+'-j'+qtag+'MVA'
            else:
                label='Pline:'+ptag+'+j'+qtag+'MVA'
        G.add_edge(int(line[0]),int(line[1]),taillabel=label)
    G.graph['graph']={'rankdir':'TD','splines':'ortho','size': (10,10),'nodesep':2.5,'forcelabels':'True'}
    G.graph['node']={'shape':'line','width':0.1,'style':'filled'}
    G.graph['edges']={'arrowsize':'4.0','labelfontcolor':'red','labeldistance':5}

    A = to_agraph(G)
    print(A)
    A.layout('dot')
    A.draw(filename)
Example #5
0
def visualize_pipeline(fname_dst, cg=COMP_GRAPH, params=DEFAULT_PARAMS):

    runner = CompGraphRunner(cg, frozen_tokens=params)

    ag = to_agraph(runner.token_manager.to_networkx())
    ag.layout('dot')
    ag.draw(fname_dst)
Example #6
0
 def paths_graph_to_Image(self):
     '''Returns PIL image of pathways graph
     
     Returns
     --------
     img: :class:`PIL.Image.Image`
     '''
     if self.paths_graph:
         fout = tempfile.NamedTemporaryFile(suffix=".png")
         agraph = to_agraph(self.paths_graph)
         agraph.graph_attr.update(ratio=1.0,
                                  overlap="ipsep",
                                  mode="ipsep",
                                  splines="true")
         try:
             agraph.layout(args="-Gepsilon=0.01 -Gmaxiter=50")
         except Exception as e:
             raise RuntimeError(
                 "There was a problem with Graphviz. See https://graphviz.gitlab.io/"
             ) from e
         if agraph.number_of_nodes() <= 200:
             agraph.draw(fout.name, prog='neato')
         else:
             agraph.draw(fout.name, prog='dot')
         img = Image.open(fout.name)
         return img
     else:
         raise RuntimeError("Nothing to draw.")
Example #7
0
def output_clustered_graph(graph, name, clustering):
    """Will ommit edge labels
    """

    # Create AGraph via networkx
    G = nx.DiGraph()
    G.add_nodes_from(graph.nodes())
    G.add_edges_from(graph.edges())

    A = to_agraph(G)

    tableau20 = [ '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78',
                  '#2ca02c', '#98df8a', '#d62728', '#ff9896',
                  '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
                  '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7',
                  '#bcbd22', '#dbdb8d', '#17becf', '#9edae5' ]
    clist = [ tableau20[i*2] for i in range(0, len(tableau20)/2)]

    i = 0
    for c in clustering:
        A.add_subgraph(c, name='cluster_%d' % i, color=clist[i % len(clist)])
        i += 1

    name = 'graphs/%s.png' % name
    A.write(name + '.dot')
    A.draw(name, prog="dot")
Example #8
0
def drawNetwork2(G, bought, name):
    G.graph['overlap'] = False
    G.graph['node'] = {'shape': 'circle'}
    G.add_nodes_from(bought, style='filled', fillcolor='lawngreen')
    G.add_nodes_from([
        node for node in G.nodes
        if node not in bought and not G.nodes[node]['immunization']
    ],
                     style='filled',
                     fillcolor='darkred')
    G.add_nodes_from([
        node for node in G.nodes
        if node not in bought and G.nodes[node]['immunization']
    ],
                     style='filled',
                     fillcolor='aqua')
    target = nx.get_node_attributes(G, 'target')
    target_node = [key for key, value in target.items() if value is True]
    G.add_nodes_from(target_node, style='filled', fillcolor='orange')
    for node in G:
        G.add_nodes_from([node], label=(str(node)))

    A = to_agraph(G)
    A.layout('dot')
    A.draw(name)
Example #9
0
    def visualizeGraph(self, residualGraph, vertex_disjoint_paths, start, end):
        A = to_agraph(residualGraph)
        A.node_attr['style'] = 'filled'

        # iterate over vertex disjoint paths
        for path in vertex_disjoint_paths:
            color = "#" + ''.join(
                [random.choice('0123456789ABCDEF') for j in range(6)])
            i = 0
            while i < len(path) - 1:
                n = A.get_node(path[i])
                n.attr['fillcolor'] = color
                n = A.get_edge(path[i], path[i + 1])
                n.attr['fillcolor'] = color
                i = i + 1
            # fill starting and ending node
        n = A.get_node(start)
        n.attr['fillcolor'] = "#d64945"
        n = A.get_node(end)
        n.attr['fillcolor'] = "#d64945"
        A.layout('dot')
        A.draw('graph.png')
        img = mpimg.imread('graph.png')
        imgplot = plt.imshow(img)
        plt.show()
def show_graph(graph_list: List[nx.DiGraph], path: str, name: str):
    count = 1
    size_list = []
    Path("./graph_{}".format(path)).mkdir(parents=True, exist_ok=True)
    for graph in graph_list:
        this_size = str(len(graph.nodes))
        size_list.append(this_size)
        try:
            nx.draw_planar(graph)  # only works if the graph is planar
        except Exception:
            nx.draw(graph)  # if the previous failed, draw nontheless
        # plt.show()
        render = to_agraph(
            graph
        )  # this is using graphviz. Graphviz worked better than matplotlib in this case.

        render.layout(
            'dot'
        )  # this is only one of the possible layouts, I will comment on this on WeChat
        # other possible layouts: http://www.adp-gmbh.ch/misc/tools/graphviz/index.html
        render.graph_attr['label'] = name + "\nnumber of vertices = " + this_size + \
                                     "\nHilbert Function result, so far: [" + fp.reduce(
            lambda a, b: str(a) + ', ' + str(b), size_list) + "]"
        render.draw('graph_{}/graph_{}.png'.format(path, count))
        count = count + 1
Example #11
0
def collate(collation, output="table", layout="horizontal", segmentation=True):
    algorithm = DekkerSuffixAlgorithm(collation)
    # build graph
    graph = VariantGraph()
    algorithm.build_variant_graph_from_blocks(graph, collation)
    # join parallel segments
    if segmentation:
        join(graph)
    # check which output format is requested: graph or table
    if output=="graph" and in_ipython:
        # visualize the variant graph into SVG format
        from networkx.drawing.nx_agraph import to_agraph
        agraph = to_agraph(graph.graph)
        svg = agraph.draw(format="svg", prog="dot", args="-Grankdir=LR -Gid=VariantGraph")
        return display(SVG(svg)) 
    # create alignment table
    table = AlignmentTable(collation, graph)
    if output == "json":
        return display_alignment_table_as_json(table)
    if output == "novisualization":
        return table
    # create visualization of alignment table
    if layout == "vertical":    
        prettytable = visualizeTableVertically(table)
    else:
        prettytable = visualizeTableHorizontal(table)
    if in_ipython():
        html = prettytable.get_html_string(formatting=True)
        return display(HTML(html))
    return prettytable
Example #12
0
def directed_graph_to_graphviz_image(dg, image_path, layout='dot', verbose=0):
    ag = to_agraph(dg)
    ag.layout(layout)
    ag.draw(image_path)
    if verbose:
        pil_im = Image.open(image_path, 'r')
        plt.imshow(pil_im)
def draw_frequent_itemsets(frquent_itemsets, network_name):
    list1 = []
    list2 = []
    g = nx.DiGraph()
    item_sets = sorted(frquent_itemsets.keys(), key=len, reverse=True)
    for item in item_sets:
        if len(item) == len(item_sets[0]):
            g.add_node(node_data(frquent_itemsets, item),
                       style='filled',
                       fillcolor=node_color(frquent_itemsets[item]))
            list1.append(item)
        else:
            if len(list1[0]) - len(item) == 2:
                list1 = list2
                list2 = []
            list2.append(item)
            g.add_node(node_data(frquent_itemsets, item),
                       style='filled',
                       fillcolor=node_color(frquent_itemsets[item]))
            for super_set in list1:
                if set(item) <= set(super_set):
                    g.add_edge(node_data(frquent_itemsets, super_set),
                               node_data(frquent_itemsets, item),
                               color='brown')
    A = to_agraph(g)
    A.layout('dot')
    A.draw(network_name)
Example #14
0
def plot_networkx(num_states, T, drug_name):
    """ This plots the Transition matrix for each condition. """
    G = nx.MultiDiGraph()
    num_states = T.shape[0]

    # node labels
    labels = {}
    for i in range(num_states):
        labels[i] = "state " + str(i + 1)

    # add nodes
    for i in range(num_states):
        G.add_node(i,
                   pos=(-2, -2),
                   label=labels[i],
                   style='filled',
                   fillcolor='lightblue')

    # add edges
    for i in range(num_states):
        for j in range(num_states):
            G.add_edge(i, j, penwidth=2 * [i, j], minlen=1)

    # add graphviz layout options (see https://stackoverflow.com/a/39662097)
    G.graph['edge'] = {'arrowsize': '0.6', 'splines': 'curved'}
    G.graph['graph'] = {'scale': '1'}

    # adding attributes to edges in multigraphs is more complicated but see
    # https://stackoverflow.com/a/26694158
    for i in range(num_states):
        G[i][i][0]['color'] = 'black'

    A = to_agraph(G)
    A.layout('dot')
    A.draw('output/' + str(drug_name) + '.svg')
Example #15
0
def draw_network(G):
    # G = nx.star_graph(20)
    # pos = nx.spring_layout(G)
    # colors = range(20)
    # nx.draw(G, pos, node_color='#A0CBE2', edge_color=colors,
    #         width=4, edge_cmap=plt.cm.Blues, with_labels=False)
    # plt.show()

    weights = []
    pos = nx.circular_layout(G)
    for i in G.edges.data("frequency"):
        weights.append(i[2])
    nx.draw(G,
            pos,
            node_color=range(len(G.nodes)),
            edge_color=weights,
            width=4,
            cmap=plt.cm.Pastel1,
            edge_cmap=plt.cm.Pastel1,
            with_labels=False)
    for p in pos:  # raise text positions
        pos[p][1] -= 0.1
    # nx.draw_networkx_labels(G, pos)
    nx.draw_networkx_edge_labels(G, pos)
    print(to_agraph(G))
    plt.show()
Example #16
0
 def add(self, graph1, graph2):
     #we use "copy" of graph1 as template for adding graph2 to it
     self.impactScore = graph1.impactScore.copy()
     graph2copy = graph2.impactScore.copy()
     colors = {}
     for node in graph1.nodes:
         if node in graph1.explicit:
             colors[node] = '#669900'
         else:
             colors[node] = '#d0f0c0'
     for term, score in self.impactScore.items():
         if term in graph2copy:
             self.impactScore[term] += graph2copy[term]
             graph2copy.pop(term)
             if term in graph2.explicit:
                 colors[term] = '#ffcc00'
             else:
                 colors[term] = '#fceea7'
     for term, score in graph2copy.items():
         self.impactScore[term] = score
         if term in graph2.explicit:
             colors[term] = '#ff0066'
         else:
             colors[term] = '#ffb6c1'
     self.nodes = self.impactScore.keys()
     self.names = {term: id_to_name[term] for term in self.nodes}
     self.miniGraph = graph.subgraph(self.nodes)
     self.gvGraph = to_agraph(self.miniGraph)
     self.setLabels()
     self.gvGraph.node_attr['style'] = 'filled'
     self.gvGraph.layout('dot')
     for term in colors:
         self.gvGraph.get_node(term).attr['color'] = colors[term]
Example #17
0
    def plot(self, plot_file_name, verbose):
        if verbose:
            # init graph
            G = nx.Graph()

            # add nodes
            for territory in self.territories.values():
                label = f'{territory.name}\nt = {territory.troops}\n{territory.ruler}'
                # label = f'{territory.name}\nt = {territory.troops}, ({territory.board_pos})'
                G.add_node(territory,
                           label=label,
                           fontsize=30,
                           pos=territory.board_pos,
                           fixedsize=True,
                           height=territory.size_on_board,
                           width=territory.size_on_board,
                           shape='oval',
                           fontcolor='#FFFFFF',
                           penwidth=35,
                           fillcolor=territory.fill_color,
                           color=territory.border_color,
                           style='filled')

            # add edges
            for path in self.paths:
                G.add_edge(path.from_territory, path.to_territory, penwidth=5)

            # convert to graphviz agraph
            A = to_agraph(G)
            A.graph_attr.update(splines='true', bgcolor='#BDBDBD')
            A.layout()

            # draw and export
            A.draw(plot_file_name)
Example #18
0
    def _draw_network(self,
                      nxgraph,
                      filename,
                      layout="dot",
                      write=True,
                      use_LR=False):
        try:
            import pygraphviz
        except (ModuleNotFoundError):
            raise ModuleNotFoundError("pygraphviz not installed.")

        pygraph = to_agraph(nxgraph)

        if use_LR:
            pygraph.graph_attr['rankdir'] = 'LR'
        else:
            pass

        pygraph.add_subgraph([self.first_smiles], rank='source')
        pygraph.layout(layout)
        if write:
            pygraph.write("input.dot")
        else:
            pass
        pygraph.draw(filename)
        return
Example #19
0
File: utils.py Project: zwcdp/pgn
def plot_graph(g, fname="graph.pdf"):
    """Plot a networkx directed multigraph

    This was not easy to do at all. Plotting directed multigraphs neatly in python is an UNSOLVED problem.

    * based on https://stackoverflow.com/a/49386888/1768248
    * adding attributes to edges in multigraphs is more complicated but see
        https://stackoverflow.com/a/26694158
    * add graphviz layout options (see https://stackoverflow.com/a/39662097)

    Parameters
    ----------
    g: A tuple (vdata, edata, connectivity)
        graph to plot
    fname: string
        filepath to save with

    Returns
    -------

    """

    g = pgn2nx(g)

    g.graph["edge"] = {"arrowsize": "0.6", "splines": "curved"}
    g.graph["node"] = {"shape": "box"}
    g.graph["graph"] = {"scale": "1"}

    a = to_agraph(g)
    a.layout("circo")  # circo was the friendliest layout for me
    a.draw(fname)
Example #20
0
	def compact_show(self,name,colors={},edges_color={}):
		A=to_agraph(self)
		try:
			if 'accept' in self.graph:
				for n in self.graph['accept']:
					node = A.get_node(n)
					node.attr['peripheries'] = 2
					
			for n in self.graph['initial']:
				node = A.get_node(n)
				node.attr['penwidth'] = 2
			for n,d in self.nodes(data=True):
				node = A.get_node(n)
				if 'label' in d:
					node.attr['label'] = str(n) + "\n" + str(d['label'])
			for n,c in colors.items():
				node = A.get_node(n)
				node.attr['color'] = c
				node.attr['style'] = 'filled'
				print n,c
			for n,c in edges_color.items():
				node = A.get_edge(*n)
				node.attr['color'] = c
				node.attr['penwidth'] = 2
				print n,c

		except Exception,e:
			print "Error on printing graph: ",e
Example #21
0
def crear_arbol(df, nombreImg):
    G = nx.DiGraph(bgcolor=background)
    global indx
    global reglasDeInferencia
    global arbol_labels
    global arbol_aristas
    arbol_aristas = []
    arbol_labels = []
    indx = 0
    reglasDeInferencia = []
    rec_crear_arbol(df, G, -1, 'f', 'Si ')

    G.graph['graph'] = {'rankdir': 'TD'}
    G.graph['node'] = {'shape': 'circle'}
    G.graph['edges'] = {'arrowsize': '4.0'}

    A = to_agraph(G)
    A.layout('dot')
    A.draw(nombreImg + '.png')
    #guardo las reglas de inferencia en un archivo
    fileReglas = open('reglas' + nombreImg + '.txt', "w")
    for i in reglasDeInferencia:
        fileReglas.write(i + '\n')
    fileReglas.close()
    #guardo el arbol en un archivo
    fileArbolLabels = open(nombreImg + 'arbolLabels.txt', "w")
    for i in arbol_labels:
        fileArbolLabels.write(str(i) + '\n')
    fileArbolLabels.close()

    fileArbolAristas = open(nombreImg + 'arbolAristas.txt', "w")
    for i in arbol_aristas:
        fileArbolAristas.write(str(i) + '\n')
    fileArbolAristas.close()
    return arbol_labels, arbol_aristas
Example #22
0
    def draw(self):
        options = {
            'node_color': 'blue',
            'node_size': 10,
            'width': 1,
            'font_size': 9
        }
        nx.draw_networkx(self.G,
                         labels=self.labeldict,
                         pos=graphviz_layout(self.G, prog='neato'),
                         with_label=True,
                         **options)
        nx.draw_networkx_edges(self.G,
                               pos=graphviz_layout(self.G, prog='neato'),
                               arrowstyle='->',
                               arrow=True)
        nx.draw_networkx_edge_labels(self.G,
                                     pos=graphviz_layout(self.G, prog='neato'),
                                     edge_labels=self.edge_label,
                                     arrowstyle='-')

        self.G.graph['graph'] = {'rankdir': 'TD', 'size': "20.,20"}
        self.G.graph['edges'] = {'arrowsize': '10.0'}
        G_agraph = to_agraph(self.G)
        G_agraph.layout(prog='dot')
        G_agraph.draw(self.filename.split('.')[0] + '.png')
        Image.open(self.filename.split('.')[0] + '.png').show()
Example #23
0
def createGraphTikz(st, eL):
    def replaceChars(s):
        return (s.replace('#', '\#').replace('#', '\\#').replace(
            u'è', 'e\'').replace(u'é', 'e\'').replace(u'ù', 'u\'').replace(
                u'ì', 'i\'').replace(u'à',
                                     'a\'').replace(u'ò',
                                                    'o\'').replace(u'’', '\''))

    G = nx.DiGraph()

    nodes = list(i for i in range(len(st)))
    edges = list((st.index(t[0]), st.index(t[1]), t[2]) for t in eL)

    G.add_nodes_from(nodes)
    G.add_weighted_edges_from(edges)
    G.graph['edge'] = {'arrowsize': '1', 'splines': 'curved'}
    G.graph['graph'] = {'scale': '1000000'}
    A = to_agraph(G)
    A.layout('dot')
    for i, s in enumerate(st):
        n = A.get_node(i)
        n.attr['label'] = replaceChars(s)
    for triplet in edges:
        e = A.get_edge(triplet[0], triplet[1])
        e.attr['label'] = toLatexProb(triplet[2])
    A.draw('image.png')
    texcode = dot2tex.dot2tex(A.to_string(), format='tikz', crop=True)
    regEx = re.compile(r'(\\begin\{tikzpicture\})(.*?)(\\end\{tikzpicture\})',
                       re.M | re.DOTALL)
    return ''.join(regEx.findall(texcode)[0])
Example #24
0
def genome_to_png(g, name, caption=None):
    if caption == None:
        caption = name
    nodes = []
    labels = []
    for n in [g.get_node(i) for i in range(len(g.nodes))]:
        nodes.append(n.innovation_number)
        labels.append(n.get_type()[0])

    connections = []
    for c in [g.get_connection(i) for i in range(len(g.connections))]:
        if c.disabled == False:
            connections.append(
                (c.from_node.innovation_number, c.to_node.innovation_number, {
                    "weight": "{:.02f}".format(c.weight)
                }))

    G = nx.MultiDiGraph()
    G.add_nodes_from(nodes)
    G.add_edges_from(connections)

    A = to_agraph(G)
    A.graph_attr["label"] = caption
    A.node_attr["shape"] = "circle"
    for i in range(len(nodes)):
        A.get_node(nodes[i]).attr["label"] = labels[i]
    for x, y, d in connections:
        A.get_edge(x, y).attr["label"] = d["weight"]
    A.layout("dot")
    A.draw("{}.png".format(name))
Example #25
0
    def handle(self, *args, **options):
        re_include = re.compile(
            "{%\s+?(include|extends)\s+?['|\"](.*?)['|\"]\s+?.*?%}", re.DOTALL)
        htmlfiles = glob.glob('**/*.html', recursive=True)

        G = nx.DiGraph()
        labels = {}
        for path in sorted(htmlfiles, key=lambda x: os.path.basename(x)):
            bpath = os.path.basename(path)
            with open(path, 'r') as datei:
                allet = datei.read()
                includes = re_include.findall(allet)
                for incl in includes:
                    if incl[0] == 'include':
                        x, y = bpath, os.path.basename(incl[1])
                        labels[(x, y)] = 'include'
                    else:
                        x, y = os.path.basename(incl[1]), bpath
                        labels[(x, y)] = 'extends'
                    G.add_edge(x, y)

        # pos = nx.spring_layout(G)
        # nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
        A = nx_agraph.to_agraph(G)
        A.graph_attr.update(rankdir='LR')
        A.draw('dependency_graph.png', prog='dot')
Example #26
0
def draw_forwarding_network(source, dst):
    network = Network()
    #cmap = matplotlib.colors.get_named_colors_mapping()
    cmap = plt.get_cmap('gnuplot')
    #LinearSegmentedColormap.from_list("", ["red","green", "blue"])
    G = nx.DiGraph()
    # adding nodes to graph
    for node in network.get_nodes_on_path(source, dst):
        G.add_node(node)
    calc_tot_send_time(network,
                       source,
                       dst,
                       greedy_mode=False,
                       fair_forwarding=True)

    for link in network.get_links_on_path(source, dst):
        link_source, link_dst = link
        penwidth = 1 + 10 * network.get_link_flow((link_source, link_dst))
        color = matplotlib.colors.rgb2hex(
            cmap(network.get_link_flow((link_source, link_dst))))
        G.add_edge(link_source, link_dst, penwidth=penwidth, color=color)

    mapping = {nodename: nodename for nodename in network.get_node_names()}
    nx.relabel_nodes(G, mapping, copy=False)
    # set defaults
    G.graph['graph'] = {'rankdir': 'TD'}
    G.graph['node'] = {'shape': 'circle'}
    G.graph['edges'] = {'arrowsize': '4.0'}
    A = to_agraph(G)
    A.layout('dot')
    data_name = dst + '_fair_pf.png'
    A.draw(data_name)
Example #27
0
    def draw_whole_network(self):
        network = list(all_subsets(''.join(self.unique_transaction.keys())))
        g = nx.DiGraph()
        g.add_node('Start', style='filled', fillcolor="red")
        for item in network[1:len(self.unique_transaction)+1]:
            g.add_node(node_data(self.frquent_itemsets, ''.join(item)), style='filled', fillcolor=node_color(
                self.frquent_itemsets[''.join(item)]) if ''.join(item) in self.frquent_itemsets else 'white')
            g.add_edge('Start', node_data(
                self.frquent_itemsets, ''.join(item)))
        for item in network[len(self.unique_transaction)+1:]:
            item = sorted(item)
            item = ''.join(item)
            g.add_node(node_data(self.frquent_itemsets, item), style='filled', fillcolor=node_color(
                self.frquent_itemsets[item]) if item in self.frquent_itemsets else 'white')
            index1 = index(len(self.unique_transaction), len(item)-2)
            index2 = index(len(self.unique_transaction), len(item)-1)

            for item2 in network[int(index1):int(index2)]:
                item2 = sorted(item2)
                item2 = ''.join(item2)
                if set(item) >= set(item2):
                    g.add_edge(node_data(self.frquent_itemsets, item2),
                               node_data(self.frquent_itemsets, item))
        A = to_agraph(g)
        A.layout('dot')
        A.draw('network.png')
Example #28
0
def graph():
    options = {
        "node_color": "#BADD8CFF",
        "edgecolors": "#8CC63FFF",
        "edge_color": "grey",
        #"connectionstyle": "arc3,rad=0.2",
        "with_labels": True
    }

    plt.get_current_fig_manager().set_window_title('Графічна форма')
    g = nx.MultiGraph()

    g.add_nodes_from(Ui_Window_2.a)
    for i in Ui_Window_2.relations_dict.keys():
        if Ui_Window_2.relations_dict[i] == 1:
            g.add_edge(i[0], i[1])
            print(i)

    a = to_agraph(g)
    a.layout('dot')
    a.draw("DisLab3/graph.png")

    # plt.savefig("temp.png")
    nx.draw(g, pos=nx.spring_layout(g), **options)
    plt.show()
Example #29
0
	def create_topology(self, backbone='zoo/Atmnet.graphml', agg_n=2, a_type='star', k=1, c=()):
		node,edge = parse_zoo(backbone)
		G = nx.Graph(edge)
		G.add_nodes_from(node)
		A=to_agraph(G)        # convert to a graphviz graph
		A.layout()            # neato layout
		A.draw("core.ps") 
		self.backbone = []
		self.aggregation = []
		self.access = { 'star':[],
						'ftree':[],
						'bcube':[]}
		self.backbone += node
		#node,edge = [0,1,2], self.create_ring(3) + [(2,0)]
		res = edge
		agg = []
		adjust = lambda x: (x[0] + num_node,x[1]+num_node)
		num_node = len(node)
		output = open('topo/{}.txt'.format(backbone),'w+')
		output.write('name: {}; backbone nodes: {}\n'.format(backbone,len(node)))
		for i in set(sum(res, ())):
			a_type = random.choice(['star','ftree','bcube'])
			if a_type == 'star':
				k = random.randint(3,7)
			if a_type == 'ftree':
				k = random.choice([2,4])
			if a_type == 'bcube':
				c = (random.randint(2,6),random.randint(0,1))
			tmp, t = self.aggregate(agg_n,a_type,k=k,c=c)
			tmp = map(adjust,tmp)
			print 'agg', self.aggregation
			self.aggregation += [x+num_node for x in range(agg_n)]
			#print tmp, [(n,tmp[0][0]),(n,tmp[0][1])]
			agg += [tmp[0][0],tmp[0][-1]]
			self.access[a_type] += tmp
			res += tmp + [(node[i],tmp[0][0]),(node[i],tmp[0][-1])]
			num_node = max(list(sum(res, ()))) + 1
			output.write('Node {}, type: {}, params: {}, nodes: {}\n'.format(i,a_type,(k,c),len(set(sum(tmp, ())))))
			#print(max(list(sum(res, ()))), num_node)
		output.close()
		'''
		elist = []
		for p in res:
			elist.append(u'{} {}'.format(p[0],p[1]))
		#print elist, len(elist)
		graph = nx.read_edgelist(elist)	
		print graph.nodes(), graph.edges(), len(graph.nodes())
		print agg
		pos = nx.spring_layout(graph)
		nx.draw_networkx(graph, pos)
		nx.draw_networkx_nodes(graph,pos,
		                       nodelist=map(str,node),
		                       node_color='g')
		nx.draw_networkx_nodes(graph,pos,
		                       nodelist=map(str,agg),
		                       node_color='y')
		plt.show()
		'''
		return res
Example #30
0
 def _snap(self, filename):
     """
         Take snapshot image of the graph
     """
     out = to_agraph(self._graph)
     out.layout(prog='dot')
     out.draw(filename + '.png')
     return np.asarray(im.open(filename + '.png'))
Example #31
0
def draw_graph(Graph, file):
    G = nx.DiGraph(Graph, directed=True)
    G.graph['graph'] = {'rankdir': 'TD'}
    G.graph['node'] = {'shape': 'box'}
    G.graph['edges'] = {'arrowsize': '4.0'}
    A = to_agraph(G)
    A.layout('dot')
    A.draw(file)
Example #32
0
def main(deep):
    global max_deep
    max_deep = deep
    game_state = np.array([[-1, 1, 4, 0, 7, 2, -1], [-1, 5, 8, 9, 3, 6, -1]])
    recursive_function(game_state, None, 0)
    A = to_agraph(G)
    A.layout('dot')
    A.draw('brute_force.png')
Example #33
0
 def plot(self, G):
     A = to_agraph(G)
     A.node_attr['style'] = 'filled'
     A.node_attr['fillcolor'] = '#000033'
     A.node_attr['shape'] = 'circle'
     #A.node_attr['fixedsize'] = 'true'
     A.node_attr['fontcolor'] = '#FFFFFF'
     A.draw('chart.png', prog='fdp')
Example #34
0
    def to_dot(self, path: Optional[str] = None) -> str:
        from networkx.drawing.nx_agraph import to_agraph

        nx = self.to_networkx()
        a = to_agraph(nx)

        if path is not None:
            a.write(path)
        return a.to_string()
Example #35
0
def draw(res,f):
	G = nx.Graph(res)
	#G.add_edges_from(res)
	for i in set(sum(res, ())):
		if i in t.backbone:
			G.add_node(i,style='filled',fillcolor='green')
		elif i in t.aggregation:
			G.add_node(i,style='filled',fillcolor='yellow')
	A=to_agraph(G)        # convert to a graphviz graph
	A.layout()            # neato layout
	A.draw("topo/zoo/"+f+".ps")
Example #36
0
def draw_test(res,struct):
	G = nx.Graph(res)
	#G.add_edges_from(res)
	for i in set(sum(res, ())):
		if i in struct['core']:
			G.add_node(i,style='filled',fillcolor='green')
		elif i in struct['agg']:
			G.add_node(i,style='filled',fillcolor='yellow')
		elif i in struct['edge']:
			G.add_node(i,style='filled',fillcolor='red')
	A=to_agraph(G)        # convert to a graphviz graph
	A.layout()            # neato layout
	A.draw("topo/test/1.ps")
    def _drawGraph(self, graph, filename):
        graphviz_graph = to_agraph(graph)

        graphviz_graph.draw(filename, prog="dot")
Example #38
0
import networkx as nx
import matplotlib.pyplot as plt
from gengraph import *

import pylab as plt
from networkx.drawing.nx_agraph import graphviz_layout, to_agraph
import pygraphviz as pgv

g = genGraph(50)

pr = nx.pagerank(g)

with open('output', 'w') as f:
  f.write(str(pr))

#print nx.info(g)

a = to_agraph(g)

print a

a.layout('dot')
a.draw('graph.png')