コード例 #1
0
def main(fn: str):
    infile = Path(f'{fn}')
    outfile = infile.parent.joinpath(infile.stem + '.pdf')
    outfilebw = infile.parent.joinpath(infile.stem + '.pdf.bw.txt')
    topo = json.loads(infile.read_text())
    nxg = nx_graph_from_topo(topo)
    pos = spring_layout(nxg, iterations=4000)
    fig = Figure()
    fig.set_dpi(300)
    ax = fig.add_subplot(111)
    ax.axis('off')
    labels = dict()
    for edge in nxg.edges:
        bw = nxg.get_edge_data(edge[0], edge[1], dict()).get('bw', None)
        bw = '' if bw is None else '%.1f mbps' % (bw, )
        labels[edge] = bw
    if len(set(labels.values())) > 1:
        draw_networkx_edge_labels(nxg,
                                  pos,
                                  ax=ax,
                                  edge_labels=labels,
                                  bbox=dict(facecolor='#FFFFFF88',
                                            edgecolor='none'),
                                  font_size='x-small')
    else:
        sbw = next(iter(set(labels.values())))
        outfilebw.write_text(sbw)
    draw_networkx_edges(nxg,
                        pos,
                        ax=ax,
                        edgelist=nxg.edges,
                        edge_color='black')
    draw_networkx_nodes(nxg,
                        pos,
                        ax=ax,
                        nodelist=topo[0],
                        node_color='lightgreen',
                        edgecolors="green")
    draw_networkx_nodes(nxg,
                        pos,
                        ax=ax,
                        nodelist=topo[1],
                        node_color='cyan',
                        edgecolors="darkcyan")
    draw_networkx_labels(nxg, pos, ax=ax, font_size='small')
    fig.savefig(str(outfile))
コード例 #2
0
ファイル: DrawNetwork.py プロジェクト: 1kastner/Tag2Network
def _draw_networkx_(G, pos=None, with_labels=True, **kwds):
    """Draw the graph G using Matplotlib.
    Draw the graph with Matplotlib with options for node positions,
    labeling, titles, and many other drawing features.
    See draw() for simple drawing without labels or axes.
    Parameters
    ----------
    G : graph
       A networkx graph
    pos : dictionary, optional
       A dictionary with nodes as keys and positions as values.
       If not specified a spring layout positioning will be computed.
       See networkx.layout for functions that compute node positions.
    with_labels :  bool, optional (default=True)
       Set to True to draw labels on the nodes.
    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.
    nodelist : list, optional (default G.nodes())
       Draw only specified nodes
    edgelist : list, optional (default=G.edges())
       Draw only specified edges
    node_size : scalar or array, optional (default=300)
       Size of nodes.  If an array is specified it must be the
       same length as nodelist.
    node_color : color string, or array of floats, (default='r')
       Node color. Can be a single color format string,
       or a  sequence of colors with the same length as nodelist.
       If numeric values are specified they will be mapped to
       colors using the cmap and vmin,vmax parameters.  See
       matplotlib.scatter for more details.
    node_shape :  string, optional (default='o')
       The shape of the node.  Specification is as matplotlib.scatter
       marker, one of 'so^>v<dph8'.
    highlight : array of boolean, if true a black ring is draw round the node
    alpha : float, optional (default=1.0)
       The node and edge transparency
    cmap : Matplotlib colormap, optional (default=None)
       Colormap for mapping intensities of nodes
    vmin,vmax : float, optional (default=None)
       Minimum and maximum for node colormap scaling
    linewidths : [None | scalar | sequence]
       Line width of symbol border (default =1.0)
    width : float, optional (default=1.0)
       Line width of edges
    edge_color : color string, or array of floats (default='r')
       Edge color. Can be a single color format string,
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.
    edge_cmap : Matplotlib colormap, optional (default=None)
       Colormap for mapping intensities of edges
    edge_vmin,edge_vmax : floats, optional (default=None)
       Minimum and maximum for edge colormap scaling
    style : string, optional (default='solid')
       Edge line style (solid|dashed|dotted,dashdot)
    labels : dictionary, optional (default=None)
       Node labels in a dictionary keyed by node of text labels
    font_size : int, optional (default=12)
       Font size for text labels
    font_color : string, optional (default='k' black)
       Font color string
    font_weight : string, optional (default='normal')
       Font weight
    font_family : string, optional (default='sans-serif')
       Font family
    label : string, optional
        Label for graph legend
    Examples
    --------
    >>> G=nx.dodecahedral_graph()
    >>> nx.draw(G)
    >>> nx.draw(G,pos=nx.spring_layout(G)) # use spring layout
    >>> import matplotlib.pyplot as plt
    >>> limits=plt.axis('off') # turn of axis
    Also see the NetworkX drawing examples at
    http://networkx.github.io/documentation/latest/gallery.html
    See Also
    --------
    draw()
    draw_networkx_nodes()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    if pos is None:
        pos = nx.drawing.spring_layout(G)  # default to spring layout

    draw_nx_nodes(G, pos, **kwds)
    draw_nx_tapered_edges(G, pos, **kwds)
    if with_labels:
        draw_networkx_labels(G, pos, **kwds)
    plt.draw_if_interactive()
コード例 #3
0
def plot(ax, currentfile):
    ax.clear()
    ax.axis('off')
    if not currentfile.exists():
        return
    toponame = currentfile.read_text().strip()
    statepath = Path(f'{toponame}.state')
    if toponame not in topos:
        topos[toponame] = json.loads(Path(f'{toponame}.json').read_text())
    topo = topos[toponame]
    if toponame not in nxgs:
        nxgs[toponame] = nx_graph_from_topo(topo)
    nxg = nxgs[toponame]
    if toponame not in topoPos:
        topoPos[toponame] = spring_layout(nxg, iterations=2000)
    pos = topoPos[toponame]
    if toponame not in topoDjkt:
        djkt = Dijkstra(graph_from_topo(topo))
        djkt_pairs = list()
        for h1 in topo[0]:
            for h2 in topo[0]:
                if h1 != h2:
                    h1, h2 = _sort_pair(h1, h2)
                    djkt_seq = djkt(h1)(h2)[0]
                    for i in range(len(djkt_seq) - 1):
                        djkt_pairs.append(_sort_pair(*djkt_seq[i:i + 2]))
        topoDjkt[toponame] = djkt_pairs
    djkt = topoDjkt[toponame]
    state_txt = ""
    if statepath.exists():
        state_txt = statepath.read_text()
    paths, path_segments, loads = parse_state(state_txt)
    labels = dict()
    for unsortededge in nxg.edges:
        edge = _sort_pair(*list(map(str, unsortededge)))
        labels[unsortededge] = "%0.4f" % (loads.get(edge, 0.0), )
        # labels[unsortededge] = repr(loads.get(edge, 0.0),)
    edlab = draw_networkx_edge_labels(nxg,
                                      pos,
                                      ax=ax,
                                      edge_labels=labels,
                                      bbox=dict(facecolor='none',
                                                edgecolor='none'))
    loaded_sws = set(topo[1]).intersection(get_loaded_switches())
    unloaded_sws = set(topo[1]).difference(loaded_sws)
    for unsortededge in nxg.edges:
        edge = _sort_pair(*list(map(str, unsortededge)))
        in_djkt = edge in djkt
        in_sgmt = min(
            1.0,
            max(
                0.0,
                path_segments.get(
                    edge, path_segments.get(tuple(reversed(edge)), 0.0))))
        in_sgmt = ('0' + (hex(round(in_sgmt * 255))[2:]))[-2:].upper()
        in_unld = (edge[0] in unloaded_sws) or (edge[1] in unloaded_sws)
        color = '#' + CLR[in_djkt] + CLR[in_unld] + in_sgmt
        draw_networkx_edges(nxg, pos, ax=ax, edgelist=[edge], edge_color=color)
    draw_networkx_nodes(nxg,
                        pos,
                        ax=ax,
                        nodelist=topo[0],
                        node_color='lightgreen')
    draw_networkx_nodes(nxg,
                        pos,
                        ax=ax,
                        nodelist=unloaded_sws,
                        node_color='pink')
    draw_networkx_nodes(nxg,
                        pos,
                        ax=ax,
                        nodelist=loaded_sws,
                        node_color='cyan')
    draw_networkx_labels(nxg, pos, ax=ax)