Ejemplo n.º 1
0
    def visualize_output(self):
        """
        Visualize Max Clique output post QAOA optimization.
        """

        # Sample output
        z, avg_cost = self.sample(vis=True)
        print('Sampled Output: ' + str(z))
        print('Minimum Cost: ' + str(self.cost_function(z)))
        print('Expectation Value: ' + str(avg_cost))

        # Extract colormap
        color_map = []
        for i in range(len(self.graph.nodes)):
            if z[i] == '0':
                color_map.append('red')
            else:
                color_map.append('blue')

        # Extract cuts
        cuts = []
        for e in self.graph.edges:
            if z[e[0]] == '1' and z[e[1]] == '1':
                cuts.append('solid')
            else:
                cuts.append('dashed')

        # Draw input graph
        fig = plt.figure(figsize=(10, 5))
        fig.suptitle('Max Clique')
        plt.subplot(121)
        ax = plt.gca()
        ax.set_title('Input Graph')
        pos = spring_layout(self.graph)
        nx.draw(self.graph,
                with_labels=True,
                node_color='lightgreen',
                edge_color='lightblue',
                style='solid',
                width=2,
                ax=ax,
                pos=pos,
                font_size=8,
                font_weight='bold')

        # Draw output graph
        plt.subplot(122)
        ax = plt.gca()
        ax.set_title('Output Graph')
        nx.draw(self.graph,
                with_labels=True,
                node_color=color_map,
                edge_color='green',
                style=cuts,
                width=2,
                ax=ax,
                pos=pos,
                font_size=8,
                font_weight='bold')
        plt.show()
Ejemplo n.º 2
0
def draw_spring(G, **kwargs):
    """Draw the graph G with a spring layout.

    Parameters
    ----------
    G : graph
       A networkx graph
    **kwargs : optional keywords
       See networkx.draw_networkx() for a description of optional keywords,
       with the exception of the pos parameter which is not used by this
       function.
    """
    draw(G, spring_layout(G), **kwargs)
Ejemplo n.º 3
0
def draw_spring(G, **kwargs):
    """Draw the graph G with a spring layout.

    Parameters
    ----------
    G : graph
       A networkx graph

    kwargs : optional keywords
       See networkx.draw_networkx() for a description of optional keywords,
       with the exception of the pos parameter which is not used by this
       function.
    """
    draw(G, spring_layout(G), **kwargs)
Ejemplo n.º 4
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))
Ejemplo n.º 5
0
def drawPlot(G, value, iter, char):
    node_colors = []
    node_sizes = []
    i = 0
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
        "", ["green", "red"])
    for node in G.nodes(data=True):
        i += 1
        try:
            print(node[1][value], i)
            # if(node[1][value] == 0):
            #     node_colors.append('navy')
            # elif(node[1][value] == 0.25):
            #     node_colors.append('blue')
            # elif(node[1][value] == 0.50):
            #     node_colors.append('green')
            # elif(node[1][value] == 0.75):
            #     node_colors.append('red')
            # elif(node[1][value] == 1):
            #     node_colors.append('darkred')
            # else:
            #     node_colors.append('black')
            node_colors.append(cmap(node[1][value]))
            node_sizes.append(node[1]['degree'])
        except KeyError:
            print(i)
    print(node_sizes)
    pos = spring_layout(G, random_state=1337)
    #cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["red","violet","blue"])
    #norm = plt.Normalize(0,1)
    nx.draw_networkx(
        G, pos=pos, with_labels=False, node_size=15, node_color=node_colors
    )  #[v*10 for v in node_sizes] , cmap=cmap, vmin=0, vmax=1)
    #plt.suptitle("Run for " + value + " for iteration: " + str(iter))
    plt.suptitle("SNAP")

    sm = plt.cm.ScalarMappable(cmap=cmap)
    sm._A = []
    plt.colorbar(sm)

    #plt.savefig("Plots/StarFixed" + char  + "/"  + value + str(iter) + ".png", dpi=1000)
    plt.savefig("SNAP" + char + ".png", dpi=1000)
    plt.clf()
Ejemplo n.º 6
0
def onion_layout(G):
    """
    Find node positions for onion-like topology

    :param networkx.Graph G: Graph
    :return: Position dictionary in networkx
    :rtype: dict
    """
    deg = G.degree()
    kd = lambda e: abs(deg[e[0]] - deg[e[1]])
    deglist = list(set(deg.values()))
    layer_idx = lambda n: deglist.index(deg[n])
    nodelist = [[] for _ in range(len(deglist))]
    for n in G.nodes_iter():
        nodelist[layer_idx(n)].append(n)
    for l in nodelist:
        tmp = l[:]
        del l[:]
        l.append(tmp.pop())
        while len(tmp) > 0:
            n = max(tmp, key=lambda n: sum(map(lambda m: m in G[n], l)))
            l.append(n)
            tmp.remove(n)

    init_pos = {}
    for li, l in enumerate(nodelist):
        dist = (1 - ((li + 1) / len(nodelist))) ** 2
        theta0 = uniform(0, 2 * pi)
        for ni, n in enumerate(l):
            theta = ni / len(l) * 2 * pi + theta0
            init_pos[n] = (dist * cos(theta), dist * sin(theta))

    # edge weight
    mindeg = lambda e: min(map(G.degree, e))
    edge_weight = dict(zip(G.edges_iter(), map(lambda e: 1 / sqrt(1 + kd(e)) * sqrt(mindeg(e)), G.edges_iter())))
    nx.set_edge_attributes(G, "weight", edge_weight)
    pos = spring_layout(G, pos=init_pos, iterations=1)
    return pos
Ejemplo n.º 7
0
def draw_spring(G, **kwargs):
    """Draw the graph G with a spring layout."""
    draw(G, spring_layout(G), **kwargs)
Ejemplo n.º 8
0

def overlapDegree(G):
    return sum(len(G.cmtyContents(c)) for c in G.cmtys()) - G.N


#
# Part 1 of tests: non-periodic.
#
gamma = 1
graph = pcd.graphs.dolphins(weightFriend=-1)
#graph = pcd.graphs.relabel_nodes(graph)

import networkx.drawing.layout as layout

layout = layout.spring_layout(graph)

G = pcd.Graph.fromNetworkX(graph, defaultweight=1, coords=layout)
G.trials(gamma=gamma, trials=10)

print G.q
print G.energy(gamma=gamma)
print sorted(G.n_counts().iteritems())

G.ovGreedy(gamma=gamma)
print G.q
print G.energy(gamma=gamma)
print sorted(G.n_counts().iteritems())

#
# Next graph: fractal square
Ejemplo n.º 9
0
 def graph_layout(self, graph):
     from networkx.drawing.layout import spring_layout
     return normalize_layout(spring_layout(graph))
Ejemplo n.º 10
0
        def make_plot(self):
            from graphion.session.handler import get_directed  # dependency cycle fix

            if get_directed(self.sid):
                G = from_pandas_adjacency(df, create_using=DiGraph)
            else:
                G = from_pandas_adjacency(df, create_using=Graph)
            self.nodeCount = number_of_nodes(G)
            """
            Create NetworkX graph layout manager
            """
            if diagramType == "FORCE":
                layout = spring_layout(G,
                                       k=10.42 / sqrt(self.nodeCount),
                                       seed=server.config['SEED'])
            elif diagramType == "HIERARCHICAL":
                if self.nodeCount > 1:
                    layout = graphviz_layout(Graph([
                        (u, v, d) for u, v, d in G.edges(data=True)
                    ]),
                                             prog='dot')
                else:
                    layout = circular_layout(
                        G
                    )  # graphviz_layout does not work with one node, just display a "circular_layout"
            elif diagramType == "RADIAL":
                layout = circular_layout(G)
            else:
                pass

            # get node and edge information from graph
            nodes, nodes_coordinates = zip(*sorted(layout.items()))
            nodes_x, nodes_y = list(zip(*nodes_coordinates))

            # calculate centrality
            centrality = degree_centrality(G)
            _, nodeCentralities = zip(*sorted(centrality.items()))

            if self.nodeCount > 1:
                # get degree information
                if is_directed(G):
                    inDegreeSize = dict(G.in_degree)
                    inDegree = inDegreeSize.copy()
                    outDegreeSize = dict(G.out_degree)
                    outDegree = outDegreeSize.copy()
                    totalDegreeSize = {}
                    for n in nodes:
                        totalDegreeSize[n] = inDegreeSize[n] + outDegreeSize[n]
                    totalDegree = totalDegreeSize.copy()
                else:
                    inDegreeSize = dict(G.degree)
                    inDegree = inDegreeSize.copy()
                    outDegreeSize = inDegreeSize.copy()
                    outDegree = inDegreeSize.copy()
                    totalDegreeSize = inDegreeSize.copy()
                    totalDegree = inDegreeSize.copy()

                # get weight information
                if is_directed(G):
                    inWeightSize = dict(G.in_degree(weight='weight'))
                    inWeight = inWeightSize.copy()
                    outWeightSize = dict(G.out_degree(weight='weight'))
                    outWeight = outWeightSize.copy()
                    totalWeightSize = {}
                    for n in nodes:
                        totalWeightSize[n] = inWeightSize[n] + outWeightSize[n]
                    totalWeight = totalWeightSize.copy()
                else:
                    inWeightSize = dict(G.degree(weight='weight'))
                    inWeight = inWeightSize.copy()
                    outWeightSize = inWeightSize.copy()
                    outWeight = inWeightSize.copy()
                    totalWeightSize = inWeightSize.copy()
                    totalWeight = inWeightSize.copy()

                # Creating a scale to ensure that the node sizes don't go bananas
                minNodeSize = 0.1  # minNodeSize * maxNodeSize = minimum node size
                maxIn = -maxsize - 1
                minIn = maxsize
                maxOut = -maxsize - 1
                minOut = maxsize
                maxTot = -maxsize - 1
                minTot = maxsize
                maxInw = -maxsize - 1
                minInw = maxsize
                maxOutw = -maxsize - 1
                minOutw = maxsize
                maxTotw = -maxsize - 1
                minTotw = maxsize
                for n in nodes:
                    ind = inDegreeSize[n]
                    outd = outDegreeSize[n]
                    totd = totalDegreeSize[n]
                    inw = inWeightSize[n]
                    outw = outWeightSize[n]
                    totw = totalWeightSize[n]
                    if ind > maxIn:
                        maxIn = ind
                    elif ind < minIn:
                        minIn = ind
                    if outd > maxOut:
                        maxOut = outd
                    elif outd < minOut:
                        minOut = outd
                    if totd > maxTot:
                        maxTot = totd
                    elif totd < minTot:
                        minTot = totd
                    if inw > maxInw:
                        maxInw = inw
                    elif inw < minInw:
                        minInw = inw
                    if outw > maxOutw:
                        maxOutw = outw
                    elif outw < minOutw:
                        minOutw = outw
                    if totw > maxTotw:
                        maxTotw = totw
                    elif totw < minTotw:
                        minTotw = totw

                if maxIn == minIn:
                    sameInDegree = True
                else:
                    sameInDegree = False
                    for n in nodes:
                        result = (inDegreeSize[n] - minIn) / maxIn
                        if result < minNodeSize:
                            inDegreeSize[n] = minNodeSize
                        else:
                            inDegreeSize[n] = result
                if maxOut == minOut:
                    sameOutDegree = True
                else:
                    sameOutDegree = False
                    for n in nodes:
                        result = (outDegreeSize[n] - minOut) / maxOut
                        if result < minNodeSize:
                            outDegreeSize[n] = minNodeSize
                        else:
                            outDegreeSize[n] = result
                if maxTot == minTot:
                    sameTotalDegree = True
                else:
                    sameTotalDegree = False
                    for n in nodes:
                        result = (totalDegreeSize[n] - minTot) / maxTot
                        if result < minNodeSize:
                            totalDegreeSize[n] = minNodeSize
                        else:
                            totalDegreeSize[n] = result
                if maxInw == minInw:
                    sameInWeight = True
                else:
                    sameInWeight = False
                    for n in nodes:
                        result = (inWeightSize[n] - minInw) / maxInw
                        if result < minNodeSize:
                            inWeightSize[n] = minNodeSize
                        else:
                            inWeightSize[n] = result
                if maxOutw == minOutw:
                    sameOutWeight = True
                else:
                    sameOutWeight = False
                    for n in nodes:
                        result = (outWeightSize[n] - minOutw) / maxOutw
                        if result < minNodeSize:
                            outWeightSize[n] = minNodeSize
                        else:
                            outWeightSize[n] = result
                if maxTotw == minTotw:
                    sameTotalWeight = True
                else:
                    sameTotalWeight = False
                    for n in nodes:
                        result = (totalWeightSize[n] - minTotw) / maxTotw
                        if result < minNodeSize:
                            totalWeightSize[n] = minNodeSize
                        else:
                            totalWeightSize[n] = result

                # Making a dictionary for all attributes, and ensuring none of the values go crazy.
                attributes = {}
                maxNodeSize = 30
                for n in nodes:
                    outd = outDegreeSize[n]
                    totd = totalDegreeSize[n]
                    inw = inWeightSize[n]
                    outw = outWeightSize[n]
                    totw = totalWeightSize[n]

                    if sameInDegree:
                        ind = 1
                    else:
                        ind = inDegreeSize[n]
                    if sameOutDegree:
                        outd = 1
                    else:
                        outd = outDegreeSize[n]
                    if sameTotalDegree:
                        totd = 1
                    else:
                        totd = totalDegreeSize[n]
                    if sameInWeight:
                        inw = 1
                    else:
                        inw = inWeightSize[n]
                    if sameOutWeight:
                        outw = 1
                    else:
                        outw = outWeightSize[n]
                    if sameTotalWeight:
                        totw = 1
                    else:
                        totw = totalWeightSize[n]

                    attributes[n] = {
                        'indegreesize': ind * maxNodeSize,
                        'outdegreesize': outd * maxNodeSize,
                        'totaldegreesize': totd * maxNodeSize,
                        'inweightsize': inw * maxNodeSize,
                        'outweightsize': outw * maxNodeSize,
                        'totalweightsize': totw * maxNodeSize,
                        'indegree': inDegree[n],
                        'outdegree': outDegree[n],
                        'totaldegree': totalDegree[n],
                        'inweight': inWeight[n],
                        'outweight': outWeight[n],
                        'totalweight': totalWeight[n],
                        'count': 0
                    }

                set_node_attributes(G, attributes)
                plot = HVGraph.from_networkx(G, layout).opts(
                    directed=get_directed(self.sid), arrowhead_length=0.01)

                # disabling displaying all node info on hovering over the node
                tooltips = [('Index', '@index'), ('In-Degree', '@indegree'),
                            ('Out-Degree', '@outdegree'),
                            ('Total Degree', '@totaldegree'),
                            ('In Edge Weight', '@inweight'),
                            ('Out Edge-Weight', '@outweight'),
                            ('Total Edge-Weight', '@totalweight')]
                hover = HoverTool(tooltips=tooltips)
            else:
                attributes = {}
                for n in nodes:
                    attributes[n] = {
                        'indegreesize': 1,
                        'outdegreesize': 1,
                        'totaldegreesize': 1,
                        'inweightsize': 1,
                        'outweightsize': 1,
                        'totalweightsize': 1,
                        'indegree': 0,
                        'outdegree': 0,
                        'totaldegree': 0,
                        'inweight': 0,
                        'outweight': 0,
                        'totalweight': 0,
                        'count': 0
                    }

                set_node_attributes(G, attributes)
                plot = HVGraph.from_networkx(G, layout).opts(
                    directed=get_directed(self.sid), arrowhead_length=0.01)
                tooltips = [('Index', '@index'), ('In-Degree', '@indegree'),
                            ('Out-Degree', '@outdegree'),
                            ('Total Degree', '@totaldegree'),
                            ('In Edge Weight', '@inweight'),
                            ('Out Edge-Weight', '@outweight'),
                            ('Total Edge-Weight', '@totalweight')]
                hover = HoverTool(tooltips=tooltips)

            # Make custom dictionary with color palettes
            for c in self.colorList:
                if c == 'cividis':
                    self.colorMap[c] = Cividis256
                elif c == 'viridis':
                    self.colorMap[c] = Viridis256
                elif c == 'inferno':
                    self.colorMap[c] = Inferno256
                else:
                    self.colorMap[c] = palette[c]

            if max(nodeCentralities) > 0:
                if datashaded and self.nodeCount > 1:
                    plot = bundle_graph(plot)
            points = plot.nodes
            points.opts(cmap=self.colorMap[self.color_palette],
                        color=self.node_color,
                        size=self.node_size,
                        tools=['box_select', 'lasso_select', 'tap', hover],
                        active_tools=['wheel_zoom'],
                        toolbar='above',
                        show_legend=False,
                        width=self.size,
                        height=self.size)

            plot.opts(node_size=0,
                      node_color=None,
                      node_line_width=0,
                      node_hover_fill_color='green')
            return plot, points
Ejemplo n.º 11
0
def catcorr(df, layout='spring', mode='mpl', titleStr='', testSig=0.05, sRange=(50, np.inf), wRange=(0.5, np.inf), labelThresh=0.05, fontsize=14):
    """Make a network plot showing the correlations among the
    categorical variables in the columns of df.

    Each node is a unique value in one of the columns
    (Node is specified as a tuple (column, value))
    Node size is proportional to the value's frequency.

    Each edge is a unique pair of values in two columns.
    Edge width is proportional to the frequency of the pairing.

    Parameters
    ----------
    df : pandas.DataFrame
        Nodes will be created for each unique value within
        each column of this object
    layout : str
        Choose one of [twopi, fdp, circo, neato, dot]
        to change the layout of the nodes.
        See Graphviz for details about each layout.
    mode : str
        Specifies whether the resulting plot will be a
        matplotlib figure (default: 'mpl')
        OR if any other value it specifies the filename
        of a figure to be posted to plot.ly
        (user needs to be logged in previously).
    titleStr : str
        Printed at the top of the plot.
    testSig : float
        If non-zero then testSig is used as the significance cutoff for plotting a highlighted edge.
        For each edge, tests the statistical hypothesis that number of observed pairings
        between values in two columns is significantly different than what one would expect
        based on their marginal frequencies. Note: there is FDR-adjustment for multiple comparisons.
    sRange,wRange : tuples of length 2
        Contains the min and max node sizes or edge widths in points, for scaling

    Examples
    --------
    >>> import plotly.plotly as py
    
    >>> py.sign_in([username], [api_key])

    >>> df = generate_test_data()

    >>> catcorr(df, layout = 'neato', mode = 'catcorr_example')

    [Posts a catcorr plot to plot.ly]

    """
    
    """Compute odds-ratios, p-values and FDR-adjusted q-values for each edge"""
    g = compute_graph(df)

    """Compute attributes of edges and nodes"""
    edgewidth = np.array([d['weight'] for n1, n2, d in g.edges(data=True)])
    nodesize = np.array([d['freq'] for n, d in g.nodes(data=True)])

    nColors = np.min([np.max([len(df.columns), 3]), 9])
    colors = palettable.colorbrewer.get_map('Set1', 'Qualitative', nColors).mpl_colors
    cmap = {c:color for c, color in zip(df.columns, itertools.cycle(colors))}
    nodecolors = [cmap[n[0]] for n in g.nodes()]
    if layout == 'twopi':
        """If using this layout specify the most common node as the root"""
        freq = {n:d['freq'] for n, d in g.nodes(data=True)}
        pos = nx.graphviz_layout(g, prog=layout, root=np.max(list(freq.keys()), key=freq.get))
    elif layout == 'spring':
        pos = spring_layout(g)
    elif layout == 'spectral':
        pos = spectral_layout(g)
    else:
        pos = nx.graphviz_layout(g, prog=layout)

    """Use either matplotlib or plot.ly to plot the network"""
    if mode == 'mpl':
        plt.clf()
        figh = plt.gcf()
        axh = figh.add_axes([0.04, 0.04, 0.92, 0.92])
        axh.axis('off')
        figh.set_facecolor('white')

        #nx.draw_networkx_edges(g,pos,alpha=0.5,width=sznorm(edgewidth,mn=0.5,mx=10), edge_color='k')
        #nx.draw_networkx_nodes(g,pos,node_size=sznorm(nodesize,mn=500,mx=5000),node_color=nodecolors,alpha=1)
        ew = szscale(edgewidth, mn=wRange[0], mx=wRange[1])

        for es, e in zip(ew, g.edges()):
            x1, y1=pos[e[0]]
            x2, y2=pos[e[1]]
            props = dict(color='black', alpha=0.4, zorder=1)
            if testSig and g[e[0]][e[1]]['qvalue'] < testSig:
                if g[e[0]][e[1]]['OR'] > 1.:
                    props['color']='orange'
                else:
                    props['color']='green'
                props['alpha']=0.8
            plt.plot([x1, x2], [y1, y2], '-', lw=es, **props)

        plt.scatter(x=[pos[s][0] for s in g.nodes()],
                    y=[pos[s][1] for s in g.nodes()],
                    s=szscale(nodesize, mn=sRange[0], mx=sRange[1]), #Units for scatter is (size in points)**2
                    c=nodecolors,
                    alpha=1, zorder=2)
        for n, d in g.nodes(data=True):
            if d['freq'] >= labelThresh:
                plt.annotate(n[1],
                            xy=pos[n],
                            fontname='Bitstream Vera Sans',
                            size=fontsize,
                            weight='bold',
                            color='black',
                            va='center',
                            ha='center')
        colorLegend(labels=df.columns,
                    colors=[c for x, c in zip(df.columns, colors)],
                    loc=0,
                    title='N = %1.0f' % (~df.isnull()).all(axis=1).sum(axis=0))
        plt.title(titleStr)
    elif PLOTLY:
        """Send the plot to plot.ly"""
        data = []
        for es, e in zip(szscale(edgewidth, mn=wRange[0], mx=wRange[1]), g.edges()):
            x1, y1=pos[e[0]]
            x2, y2=pos[e[1]]
            props = dict(color='black', opacity=0.4)
            if testSig and g[e[0]][e[1]]['qvalue'] < testSig:
                if g[e[0]][e[1]]['OR'] > 1.:
                    props['color']='orange'
                else:
                    props['color']='green'
                props['opacity']=0.8
            tmp = pygo.Scatter(x=[x1, x2],
                          y=[y1, y2],
                          mode='lines',
                          line=pygo.Line(width=es, **props),
                          showlegend=False)
            data.append(tmp)
        """May need to add sqrt() to match mpl plots"""
        nodesize = szscale(nodesize, mn=sRange[0], mx=sRange[1]) #Units for plotly.Scatter is (size in points)
        for col in list(cmap.keys()):
            ind = [nodei for nodei, node in enumerate(g.nodes()) if node[0]==col]
            tmp = pygo.Scatter(x=[pos[s][0] for nodei, s in enumerate(g.nodes()) if nodei in ind],
                    y=[pos[s][1] for nodei, s in enumerate(g.nodes()) if nodei in ind],
                    mode='markers',
                    name=col,
                    text=[node[1] for nodei, node in enumerate(g.nodes()) if nodei in ind],
                    textposition='middle center',
                    marker=pygo.Marker(size=nodesize[ind],
                                  color=[color2str(nc) for nodei, nc in enumerate(nodecolors) if nodei in ind]))
            data.append(tmp)
        layout = pygo.Layout(title=titleStr,
                        showlegend=True,
                        xaxis=pygo.XAxis(showgrid=False, zeroline=False),
                        yaxis=pygo.YAxis(showgrid=False, zeroline=False))

        fig = pygo.Figure(data=data, layout=layout)
        plot_url = py.plot(fig, filename='catcorr_'+mode)
Ejemplo n.º 12
0
G.add_node("again", size=10)
G.add_node("please", weight=0.4, UTM=("13S", 382871, 3972649))
G.add_node("aa")
G.add_edge("hello", "there", weight=0.6)
G.add_edge("there", "again", weight=0.4)
G.add_edge("there", "please", weight=0.2)
G.add_edge("hello", "aa", weight=0.2)
print(G.nodes())
print(G.edges())
# print G.info()

print(dir(lay))
res01 = lay.circular_layout(G)
print("res01", res01)
print()
res02 = lay.spring_layout(G)
print("res02", res02)
print()
print("sorted! ")

# P.topological_sort(G)
# P.topological_sort_recursive(G)

nx = NX

"""
 ANDY NOTE: requires graphviz which doesn't come easy under windows
 
# Added from example http://networkx.lanl.gov/examples/drawing/atlas.html
print("graph has %d nodes with %d edges"\
	  %(nx.number_of_nodes(G),nx.number_of_edges(G)))
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
# Build input graph
V = list(range(7))
E = [(0, 5), (0, 2), (1, 2), (1, 3), (2, 5), (2, 6), (3, 5), (3, 4), (4, 5),
     (4, 6)]
G = nx.Graph()
G.add_nodes_from(V)
G.add_edges_from(E)

# Draw input graph
fig = plt.figure(figsize=(10, 5))
fig.suptitle('Max Cut')
plt.subplot(121)
ax = plt.gca()
ax.set_title('Input Graph')
pos = spring_layout(G)
nx.draw(G,
        with_labels=True,
        node_color='lightgreen',
        edge_color='lightblue',
        style='solid',
        width=2,
        ax=ax,
        pos=pos,
        font_size=8,
        font_weight='bold')

# Generate QAOA clauses
clauses = []
for i in range(len(E)):
    edge = E[i]
Ejemplo n.º 15
0
def draw_spring(G, **kwargs):
    """Draw the graph G with a spring layout."""
    draw(G,spring_layout(G),**kwargs)
Ejemplo n.º 16
0
def draw_spring(G, **kwargs):
    """Draw the graph G with a spring layout"""
    from networkx.drawing.layout import spring_layout
    draw(G,spring_layout(G),**kwargs)
Ejemplo n.º 17
0
 def graph_layout(self, graph):
     from networkx.drawing.layout import spring_layout
     return normalize_layout(spring_layout(graph))
def draw_spring(G, **kwargs):
    """Draw the graph G with a spring layout"""
    from networkx.drawing.layout import spring_layout
    draw(G, spring_layout(G), **kwargs)
Ejemplo n.º 19
0
G.add_node("again", size=10)
G.add_node("please", weight=0.4, UTM=("13S", 382871, 3972649))
G.add_node("aa")
G.add_edge("hello", "there", weight=0.6)
G.add_edge("there", "again", weight=0.4)
G.add_edge("there", "please", weight=0.2)
G.add_edge("hello", "aa", weight=0.2)
print G.nodes()
print G.edges()
# print G.info()

print dir(lay)
res01 = lay.circular_layout(G)
print "res01", res01
print
res02 = lay.spring_layout(G)
print "res02", res02
print
print "sorted! "

# P.topological_sort(G)
# P.topological_sort_recursive(G)

nx = NX

"""
 ANDY NOTE: requires graphviz which doesn't come easy under windows
 
# Added from example http://networkx.lanl.gov/examples/drawing/atlas.html
print("graph has %d nodes with %d edges"\
	  %(nx.number_of_nodes(G),nx.number_of_edges(G)))
Ejemplo n.º 20
0
def generate3DDiagram(file, sid, df=False):
    if not df:
        df = decreaseDiagramSize(file)
    else:
        df = file

    names = df.columns.tolist()
    N = len(names)

    G = from_pandas_adjacency(df)
    G = convert_node_labels_to_integers(G)
    # 3d spring layout
    pos = spring_layout(G, dim=3)
    # numpy array of x,y,z positions in sorted node order
    layt = array([pos[v] for v in sorted(G)])
    # scalar colors
    scalars = array(list(G.nodes())) + 5
    # edges

    maximum = 0
    for (u, v, d) in G.edges(data=True):
        w = d['weight']
        if w > maximum:
            maximum = w

    Edges = array([(int(u), int(v), {
        'weight': d['weight'] / maximum
    }) for (u, v, d) in G.edges(data=True) if d['weight'] > 0])

    def make_edge(x, y, z, weight):
        return Scatter3d(
            x=x,
            y=y,
            z=z,
            # line=dict(color='rgb(' + str(int(100 + (weight ** 2 - 0.25) * 100)) + ',100,100)', width=(weight * 3) ** 2),
            line=dict(color='rgb(' + str(int(weight) * 180) + ', 0, 0)',
                      width=(weight * 3)**2),
            hoverinfo='none',
            mode='lines')

    Xn = [layt[k][0] for k in range(N)]  # x-coordinates of nodes
    Yn = [layt[k][1] for k in range(N)]  # y-coordinates
    Zn = [layt[k][2] for k in range(N)]  # z-coordinates
    edge_traces = []

    for e in Edges:
        x_edge_ends = [layt[e[0]][0], layt[e[1]][0],
                       None]  # x-coordinates of edge ends
        y_edge_ends = [layt[e[0]][1], layt[e[1]][1], None]
        z_edge_ends = [layt[e[0]][2], layt[e[1]][2], None]
        edge_traces.append(
            make_edge(x_edge_ends, y_edge_ends, z_edge_ends, e[2]['weight']))

    trace2 = Scatter3d(x=Xn,
                       y=Yn,
                       z=Zn,
                       mode='markers',
                       marker=dict(symbol='circle',
                                   size=6,
                                   color=scalars,
                                   colorscale='Viridis',
                                   line=dict(color='rgb(50,50,50)',
                                             width=0.5)),
                       text=names,
                       hoverinfo='text')

    axis = dict(showbackground=False,
                showline=False,
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                title='')

    from graphion.session.handler import calculate_plot_size
    psize = calculate_plot_size(sid)

    layout = Layout(title="Force-directed layout",
                    width=psize,
                    height=psize,
                    showlegend=False,
                    scene=dict(
                        xaxis=dict(axis),
                        yaxis=dict(axis),
                        zaxis=dict(axis),
                    ),
                    margin=dict(t=100),
                    hovermode='closest',
                    paper_bgcolor='rgba(0,0,0,0)',
                    plot_bgcolor='rgba(0,0,0,0)')

    data = [trace2] + edge_traces
    fig = Figure(data=data, layout=layout)
    extension('plotly')
    painful = Plotly(fig)
    return painful