Ejemplo n.º 1
0
    def test_bipartite_layout(self):
        G = nx.complete_bipartite_graph(3, 5)
        top, bottom = nx.bipartite.sets(G)

        vpos = nx.bipartite_layout(G, top)
        assert len(vpos) == len(G)

        top_x = vpos[list(top)[0]][0]
        bottom_x = vpos[list(bottom)[0]][0]
        for node in top:
            assert vpos[node][0] == top_x
        for node in bottom:
            assert vpos[node][0] == bottom_x

        vpos = nx.bipartite_layout(G,
                                   top,
                                   align='horizontal',
                                   center=(2, 2),
                                   scale=2,
                                   aspect_ratio=1)
        assert len(vpos) == len(G)

        top_y = vpos[list(top)[0]][1]
        bottom_y = vpos[list(bottom)[0]][1]
        for node in top:
            assert vpos[node][1] == top_y
        for node in bottom:
            assert vpos[node][1] == bottom_y

        pytest.raises(ValueError, nx.bipartite_layout, G, top, align='foo')
Ejemplo n.º 2
0
    def test_bipartite_layout(self):
        G = nx.complete_bipartite_graph(3,5)
        top, bottom = nx.bipartite.sets(G)

        vpos = nx.bipartite_layout(G, top)
        assert_equal(len(vpos), len(G))

        top_x = vpos[list(top)[0]][0]
        bottom_x = vpos[list(bottom)[0]][0]
        for node in top:
            assert_equal(vpos[node][0], top_x)
        for node in bottom:
            assert_equal(vpos[node][0], bottom_x)

        vpos = nx.bipartite_layout(G, top,
                                   align='horizontal',
                                   center=(2,2),
                                   scale=2,
                                   aspect_ratio=1)
        assert_equal(len(vpos), len(G))

        top_y = vpos[list(top)[0]][1]
        bottom_y = vpos[list(bottom)[0]][1]
        for node in top:
            assert_equal(vpos[node][1], top_y)
        for node in bottom:
            assert_equal(vpos[node][1], bottom_y)

        assert_raises(ValueError, nx.bipartite_layout, G, top, align='foo')
Ejemplo n.º 3
0
 def test_smoke_empty_graph(self):
     G = []
     nx.random_layout(G)
     nx.circular_layout(G)
     nx.planar_layout(G)
     nx.spring_layout(G)
     nx.fruchterman_reingold_layout(G)
     nx.spectral_layout(G)
     nx.shell_layout(G)
     nx.bipartite_layout(G, G)
     nx.spiral_layout(G)
     nx.kamada_kawai_layout(G)
Ejemplo n.º 4
0
def generate_bipartite_graph(n, m, p, visualize=False):
    graph = nx.algorithms.bipartite.generators.random_graph(n, m, p)
    print(graph.edges)
    if visualize:
        nx.draw(graph, pos=nx.bipartite_layout(graph, list(graph.nodes)[:n]))
        plt.show()
    return Graph(graph)
Ejemplo n.º 5
0
def complete_bipartite_graph(n, m=None):
    if m is None:
        m = n
    G = nx.complete_bipartite_graph(m, n)
    G.name = 'bipartite'
    G.graph['pos'] = nx.bipartite_layout(G, nx.bipartite.sets(G)[0])
    return G
Ejemplo n.º 6
0
def generateRandomBipartiteGraph(n, m, k):
    # create new NMK graph:
    # n = number of nodes in first bipartite set (numElectrodes)
    # m = number of nodes in second bipartite set (numWires)
    # k = number of edges (numValidEdges)
    graph = nx.bipartite.gnmk_random_graph(n, m, k)

    while (not nx.is_connected(graph)):
        graph = nx.bipartite.gnmk_random_graph(n, m, k)

    # isolate top nodes for pos dictionary definition
    top = [
        node for node in graph.nodes() if graph.nodes[node]['bipartite'] == 0
    ]

    # create dictionary for bipartite graph layout
    pos = nx.bipartite_layout(graph, top)

    # assign colors to the two node sets
    color_dict = {0: 'r', 1: 'b'}
    color_list = [color_dict[i[1]] for i in graph.nodes.data('bipartite')]

    # draw graph
    nx.draw(graph, pos, node_color=color_list)
    #plt.show()
    plt.close()

    # return graph and set of equivalent electrode nodes for analysis
    return [graph, top]
Ejemplo n.º 7
0
def draw_MI(M, ax, layout="spring"):
    M[M < 1e-15] = 0.0
    M[M < np.median(M)] = 0
    G = nx.from_numpy_matrix(M)

    if layout == "spring":
        pos = nx.spring_layout(G)
    elif layout == "bipartite":
        pos = nx.bipartite_layout(G, nodes=range(len(M) // 2))
    elif layout == "circular":
        pos = nx.circular_layout(G)

    edges, weights = zip(*nx.get_edge_attributes(G, "weight").items())
    ws = np.array([w for w in weights])
    mx = max(ws)
    mn = min(ws)
    if mx != mn:
        ws = (ws - mn) / (mx - mn)
    nx.draw(
        G,
        pos,
        ax=ax,
        node_color="k",
        node_size=6,
        alphs=0.5,
        edgelist=edges,
        edge_color="k",
        width=ws,
    )
Ejemplo n.º 8
0
def main():
    # build marvel.gml file
    # parse_xml_to_gml()
    g = nx.read_gml("marvel.gml")

    # circular layout implemented by the circular_layout
    pos_1 = nx.circular_layout(g)
    nx.draw(g, pos_1, with_labels=True, node_size=30, font_size=8, width=0.5)
    plt.show()

    # spring layout
    pos_2 = nx.spring_layout(g, k=1)
    nx.draw(g, pos_2, with_labels=True, node_size=30, font_size=8, width=0.5)
    plt.show()

    # kamada kawai layout
    pos_3 = nx.kamada_kawai_layout(g)
    nx.draw(g, pos_3, with_labels=True, node_size=30, font_size=8, width=0.5)
    plt.figure(figsize=(12, 12))
    plt.show()

    # bipartite layout
    top = nx.bipartite.sets(g)[0]
    pos_4 = nx.bipartite_layout(g, top)
    nx.draw(g, pos_4, with_labels=True, node_size=30, font_size=8, width=0.5)
    plt.show()
Ejemplo n.º 9
0
def draw_graph(graph, title='Graph'):

    G = nx.Graph()

    node_to_id_dict = {}

    next_id = 0
    for node in graph.nodes:
        G.add_node(next_id)
        node_to_id_dict[node] = next_id
        next_id += 1

    edge_labels = {}

    for edge in graph.edges:
        G.add_edge(node_to_id_dict[edge.node1], node_to_id_dict[edge.node2])
        edge_labels[(node_to_id_dict[edge.node1],
                     node_to_id_dict[edge.node2])] = edge.weight

    plt.title(title)

    left_nodes = [
        node_to_id_dict[n] for n in graph.nodes if n.node_class.is_left
    ]
    pos = nx.bipartite_layout(G, left_nodes)
    nx.draw(G, pos, with_labels=True)
    nx.draw_networkx_edge_labels(
        G, pos, edge_labels=edge_labels)  # Display edge weights as labels
    plt.axis('off')  # Turn off default matplotlib chart axis
    plt.show()
Ejemplo n.º 10
0
def plot_trades_as_graph(
        bids: pd.DataFrame,
        transactions: pd.DataFrame,
        ax=None):
    """Plots all the bids as a bipartit graph
    with buyers and trades and an edge between
    each pair that traded

    Parameters
    ----------
    bids
        Collection of bids to be used
    transactions
        Collection of transactions to be used
    ax
        The axe in which the figure should be ploted

    Returns
    -------
     axe : matplotlib.axes._subplots.AxesSubplot
        The axe in which the figure was plotted.

    """
    bids = bids.get_df()
    tmp = transactions.get_df()
    tmp['user_1'] = tmp.bid.map(bids.user)
    tmp['user_2'] = tmp.source.map(bids.user)
    tmp['buying'] = tmp.bid.map(bids.buying)
    buyers = bids.loc[bids['buying']].index.values

    G = nx.from_pandas_edgelist(tmp, 'user_1', 'user_2')

    edge_labels = {}
    duplicated_labels = tmp.set_index(
        ['user_1', 'user_2'])['quantity'].to_dict()
    for (x, y), v in duplicated_labels.items():
        if ((x, y) not in edge_labels and (y, x) not in edge_labels):
            edge_labels[(x, y)] = v

    if ax is None:
        fig, ax = plt.subplots(figsize=(8, 6))

    pos = nx.bipartite_layout(G, buyers, align='horizontal', scale=3)
    _ = nx.draw_networkx_nodes(
        G,
        pos=pos,
        ax=ax,
        node_color='k',
        node_size=500)
    _ = nx.draw_networkx_labels(G, pos=pos, ax=ax, font_color='w')
    _ = nx.draw_networkx_edges(G, pos=pos, label=G, ax=ax)
    _ = nx.draw_networkx_edge_labels(
        G,
        pos=pos,
        edge_labels=edge_labels,
        label_pos=0.9,
        ax=ax)
    _ = ax.axis('off')

    return ax
Ejemplo n.º 11
0
def generateBipartiteGraph(e_node_set, w_node_set, edge_set):

    # initialize graph
    graph = nx.Graph()

    # add nodes to the graph
    graph.add_nodes_from(e_node_set, bipartite=0)  # electrode node set
    graph.add_nodes_from(w_node_set, bipartite=1)  # wire node set

    # add edges
    graph.add_edges_from(edge_set)

    # create dictionary for bipartite graph layout
    pos = nx.bipartite_layout(graph, nx.bipartite.sets(graph)[0])

    # assign colors to the two node sets
    color_dict = {0: 'r', 1: 'b'}
    color_list = [color_dict[i[1]] for i in graph.nodes.data('bipartite')]

    # draw graph
    nx.draw(graph, pos, with_labels=True, node_color=color_list)
    #plt.show()
    plt.close()

    # return graph and set of electrode nodes (for analysis)
    return [graph, nx.bipartite.sets(graph)[0]]
Ejemplo n.º 12
0
    def __init__(self, n, m, p, graph=None):
        if graph is not None:
            self.graph = graph
            self.n = n
            self.m = m
        else:
            graph = nx.algorithms.bipartite.generators.random_graph(n, m, p)
            for i in range(n):
                graph.node[i]['value'] = np.random.uniform(-1, 1)

            for i in range(n):
                graph.node[i]['gamma'] = 0.05  # np.random.uniform(0.0,0.1)

            self.graph = graph
            self.n = n
            self.m = m
            self.p = p

            graph.node[0]['value'] = 1
            graph.node[0]['gamma'] = 0.05

        self.bar_aggregation = np.average
        # top = nx.bipartite.sets(self.graph)[0]
        # pos = nx.bipartite_layout(self.graph, top)
        # nx.draw(self.graph, pos=pos)  # use spring layout
        # plt.show()

        self.fig, self.ax = plt.subplots(figsize=(10, 10))
        top = nx.bipartite.sets(self.graph)[0]
        self.pos = nx.bipartite_layout(self.graph, top)
Ejemplo n.º 13
0
def generateSpectralLayout(layout: Layout):
    positions = nx.spectral_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.planar_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.circular_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.bipartite_layout(layout.G, nx.bipartite.sets(layout.G)[0])
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.shell_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.random_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()

    positions = nx.spiral_layout(layout.G)
    print(positions)
    nx.draw(layout.G, positions)
    plt.show()
def visualize(network, class_id, step, simulated=True):
    """
    Args:
        network: NetworkX DiGraph
        class_id: the unique id of class
        step: a number between 0 and NUM_STEP
        simulated: False if it is a real network
    """

    plt.figure(figsize=(25, 8))
    plt.tight_layout()
    plt.suptitle('Simulated on Class {}, Step {}'.format(class_id, step),
                 fontsize=30)

    females = [
        idx for idx, sex in nx.get_node_attributes(network, 'sex').items()
        if sex == 'female'
    ]
    males = [
        idx for idx, sex in nx.get_node_attributes(network, 'sex').items()
        if sex == 'male'
    ]
    male_network = network.subgraph(males)
    female_network = network.subgraph(females)

    all_edges = set(network.edges())
    female_edges = set(female_network.edges())
    male_edges = set(male_network.edges())

    # Draw network in bipartite layout, removing edges between female agents or male agents
    edgelist = all_edges - female_edges - male_edges
    plt.subplot(131)
    plt.axis('off')
    pos = nx.bipartite_layout(network, females)
    nx.draw_networkx_nodes(G=network,
                           nodelist=females,
                           pos=pos,
                           with_labels=False,
                           node_color='r')
    nx.draw_networkx_nodes(G=network,
                           nodelist=males,
                           pos=pos,
                           with_labels=False,
                           node_color='b')
    nx.draw_networkx_edges(G=network, edgelist=edgelist, pos=pos)

    # Draw network of only male agents
    plt.subplot(132)
    plt.axis('off')
    nx.draw_networkx(G = male_network, pos = nx.kamada_kawai_layout(male_network), \
                    with_labels = False, node_color = 'b')

    # Draw network of only female agents
    plt.subplot(133)
    plt.axis('off')
    nx.draw_networkx(G = female_network, pos = nx.kamada_kawai_layout(female_network), \
                     with_labels = False, node_color = 'r')

    plt.savefig('Class{}step{}.png'.format(class_id, step))
Ejemplo n.º 15
0
def plot_bipgraph(graph):
    top_nodes = set(n for n,d in graph.nodes(data='bipartite') if d==0)
    color_list = ['#aa4444','#8866aa']
    colors = [color_list[node[1]] for node in graph.nodes(data='bipartite')]
    pos = nx.bipartite_layout(graph,top_nodes)
    nx.draw_networkx(graph,pos,with_labels=True,node_size=500,node_color=colors)
    plt.axis('off')
    plt.show()
Ejemplo n.º 16
0
 def __get_pos(self, G):
     if self._name == 'petersen':
         return nx.shell_layout(G, nlist=[range(6, 11),
                                          range(1, 6)])
     if self._name == 'bipartite':
         top = nx.bipartite.sets(G)[0]
         return nx.bipartite_layout(G, top)
     return nx.circular_layout(G)
Ejemplo n.º 17
0
def small_3regular_graph(visualize=False):
    edges = [(6, 9), (6, 4), (6, 0), (9, 3), (9, 0), (1, 3), (1, 5), (1, 7),
             (3, 8), (4, 7), (4, 2), (7, 0), (2, 8), (2, 5), (8, 5)]
    graph = nx.Graph()
    graph.add_nodes_from(list(range(10)))
    graph.add_edges_from(edges)
    if visualize:
        nx.draw(graph, pos=nx.bipartite_layout(graph, list(graph.nodes)[:5]))
        plt.show()
    return Graph(graph)
Ejemplo n.º 18
0
def topSortDAG(G):

    try:
        print(list(nx.topological_sort(G)))
        top = nx.bipartite.sets(G)[0]
        pos = nx.bipartite_layout(G, top)
        nx.draw(G, pos, with_labels=True, font_weight='bold')
        plt.show()
    except:
        print("Input data is inconsistent")
Ejemplo n.º 19
0
    def draw(self):
        """
        Draws the current state & checks for deadlock
        """
        # clears old data before drawing again
        plt.clf()
        plt.axis('off')

        # get list of processes and resources
        processes = self.processDict.keys()

        # get edges (list of tuples)
        edges = []      # Owned resources
        for key in self.processDict:
            for value in self.processDict[key]:
                edges.append((value,key))

        # print(processes)
        # print("edges: ", edges)
        # print("waitingList: ", self.waitingList)

        # Read nodes/edges into networkx and draw
        self.G.add_nodes_from(processes + self.resourceList)
        self.G.add_edges_from(edges+self.waitingList)
        pos = nx.bipartite_layout(self.G, nodes=processes,align='horizontal')
        nx.draw_networkx(self.G, pos, nodelist=self.resourceList,
                            node_color='y',node_size=600,with_labels=True,
                            label="Resources",edgelist=edges,edge_color='g',
                            alpha=1)
        nx.draw_networkx(self.G, pos, nodelist=processes,
                            node_color='r',node_size=600,with_labels=True,
                            label="Processes",edgelist=self.waitingList,edge_color='b',
                            alpha=1)

        # Check for deadlock!
        # get list of cycles from networkx graph
        cycles = list(nx.simple_cycles(self.G))
        # print("cycles: ",cycles)
        # print("processes: ", self.processDict.keys())

        for cycleList in cycles:
            # get nodes from cycle list
            if len(cycleList) > 2:
                for node in cycleList:
                    if node in self.processDict.keys() and node not in self.lockedProcesses:
                        self.lockedProcesses.append(node)
        # check for system deadlock
        if len(self.lockedProcesses) == self.processes:
            self.deadlocked = True
            return
        # else list locked processes
        elif len(self.lockedProcesses) > 0:
            print("Locked Processes: ", self.lockedProcesses)

        plt.waitforbuttonpress()
Ejemplo n.º 20
0
def draw_graph(bus_route, pos_mode=0, top=[]):
    edge_list = bus_route.NETWORK_EDGES
    fig = plt.figure()
    graph = nx.DiGraph()
    color_list = []
    edges_1_list, edges_2_list = sort_edges(edge_list)
    graph.add_edges_from(edge_list)
    graph_tag = ''
    if pos_mode == 1:
        pos = nx.spring_layout(graph, k=1, iterations=3)
        graph_tag = '_spring'
    elif pos_mode == 2:
        print("Please input the id of fog nodes:")
        node_cnt = 0
        for node in bus_route.BUS_STATIONS:
            print("%d: %s" % (node_cnt, node))
            node_cnt += 1
        nodes_string = input("Input the id of fog nodes: ")
        nodes_list = nodes_string.split(',')
        for id_index in nodes_list:
            top.append(bus_route.BUS_STATIONS[int(id_index)])
        print(top)
        pos = nx.bipartite_layout(graph, top, align='horizontal')
        graph_tag = '_bipartite'
    else:
        graph_tag = '_kamada_kawai'
        pos = nx.kamada_kawai_layout(graph)
    # __logger__.debug(graph.edges().data('color'))
    for edge in graph.edges():
        if edge in edges_1_list:
            color_list.append('black')
        if edge in edges_2_list:
            color_list.append('red')
    # __logger__.debug(color_list)
    nx.draw_networkx_edges(graph,
                           pos,
                           edge_color=color_list,
                           arrows=True,
                           arrowsize=15)
    nx.draw_networkx_nodes(graph, pos, node_size=500, node_shape='o')
    nx.draw_networkx_labels(graph, pos)
    plt.xticks([])
    plt.yticks([])
    plt.axis('off')
    fig.tight_layout()
    plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
    save_path = 'graph/' + ARGS.file[9:-4] + graph_tag + '.eps'
    plt.savefig(
        save_path,
        format='eps',
        frameon=False,
        pad_inches='tight',
        # bbox_inches='tight')
    )
    plt.close()
Ejemplo n.º 21
0
 def test_smoke_empty_graph(self):
     G = []
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.spectral_layout(G)
     vpos = nx.shell_layout(G)
     vpos = nx.bipartite_layout(G, G)
     if self.scipy is not None:
         vpos = nx.kamada_kawai_layout(G)
def draw_bipartite_graph(G):
    """
		Draws the bipartite graph with unweighted edges
	"""

    top, bot = nx.bipartite.sets(G)
    pos = nx.bipartite_layout(G, top)
    nx.draw_networkx(G, pos=pos)
    plt.show()

    return
def draw_bipartite_graph(graph, first_node_set):
    pos = nx.bipartite_layout(graph, first_node_set)
    # get adjacency matrix
    A = nx.adjacency_matrix(graph)
    A = A.toarray()
    # plot adjacency matrix
    plt.imshow(A, cmap='Greys')
    plt.show()
    # plot graph visualisation
    nx.draw(graph, pos, with_labels=False)
    plt.show()
Ejemplo n.º 24
0
def small_bipartite_graph(visualize=False):
    edges = [(0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 5), (1, 6), (1, 7),
             (1, 8), (1, 9), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 5),
             (3, 7), (3, 8), (3, 9), (4, 5), (4, 6), (4, 7), (4, 9)]
    graph = nx.Graph()
    graph.add_nodes_from(list(range(10)))
    graph.add_edges_from(edges)
    if visualize:
        nx.draw(graph, pos=nx.bipartite_layout(graph, list(graph.nodes)[:5]))
        plt.show()
    return Graph(graph)
Ejemplo n.º 25
0
 def test_smoke_empty_graph(self):
     G = []
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.spectral_layout(G)
     vpos = nx.shell_layout(G)
     vpos = nx.bipartite_layout(G, G)
     if self.scipy is not None:
         vpos = nx.kamada_kawai_layout(G)
Ejemplo n.º 26
0
def draw_MI(M_orig, ax, layout="spring", pos=None):
    M = copy(M_orig)
    M[np.abs(M) < 1e-5] = 0.0
    M[np.abs(M) < np.median(M)] = 0.0
    G = nx.from_numpy_matrix(M)
    if pos is None:
        if layout == "spring":
            pos = nx.spring_layout(G, k=0.8 / np.sqrt(len(M)), iterations=74)
        elif layout == "bipartite":
            pos = nx.bipartite_layout(G, nodes=range(len(M) // 2))
        elif layout == "circular":
            pos = nx.circular_layout(G)
        elif layout == "spectral":
            pos = nx.spectral_layout(G)
        elif layout == "spiral":
            pos = nx.spiral_layout(G)
        elif layout == "shell":
            pos = nx.shell_layout(G)
        elif layout == "planar":
            pos = nx.planar_layout(G)
        elif layout == "fr":
            pos = nx.fruchterman_reingold_layout(G)
        elif layout == "kk":
            pos = nx.kamada_kawai_layout(G)
        if layout == "grid":
            Ggrid = nx.grid_2d_graph(*M.shape)
            xs = np.linspace(-1, 1, int(np.ceil(np.sqrt(len(M)))))
            pos = {}
            i = 0
            for x in xs:
                for y in xs:
                    if i < len(M):
                        pos[i] = np.array([x, y])
                    i += 1

    edges, weights = zip(*nx.get_edge_attributes(G, "weight").items())
    ws = np.array([w for w in weights])
    mx = max(ws)
    mn = min(ws)
    if mx != mn:
        ws = (ws - mn) / (mx - mn)
    nx.draw(
        G,
        pos,
        ax=ax,
        node_color="k",
        node_size=6,
        alphs=0.5,
        edgelist=edges,
        edge_color="k",
        width=ws,
    )
    ax.set_aspect("equal")
Ejemplo n.º 27
0
def medium_3regular_graph(visualize=False):
    edges = [(4, 7), (4, 10), (4, 15), (7, 15), (7, 2), (10, 11), (10, 12),
             (11, 9), (11, 5), (2, 5), (2, 3), (5, 14), (3, 14), (3, 6),
             (14, 15), (12, 0), (12, 8), (9, 1), (9, 13), (6, 8), (6, 13),
             (1, 13), (1, 0), (0, 8)]
    graph = nx.Graph()
    graph.add_nodes_from(list(range(10)))
    graph.add_edges_from(edges)
    if visualize:
        nx.draw(graph, pos=nx.bipartite_layout(graph, list(graph.nodes)[:5]))
    plt.show()
    return Graph(graph)
Ejemplo n.º 28
0
def medium_bipartite_graph(visualize=False):
    edges = [(0, 7), (0, 8), (0, 9), (0, 12), (0, 13), (1, 7), (1, 8), (1, 10),
             (1, 11), (1, 12), (1, 13), (2, 7),
             (2, 8), (2, 9), (2, 10), (2, 12), (2, 13), (3, 7), (3, 8), (3, 9),
             (3, 10), (4, 8), (4, 11), (4, 12), (4, 13), (5, 8), (5, 10),
             (5, 11), (6, 7), (6, 8), (6, 10), (6, 11), (6, 13)]
    graph = nx.Graph()
    graph.add_nodes_from(list(range(10)))
    graph.add_edges_from(edges)
    if visualize:
        nx.draw(graph, pos=nx.bipartite_layout(graph, list(graph.nodes)[:5]))
        plt.show()
    return Graph(graph)
Ejemplo n.º 29
0
def geraLayout(key, G):
    if key == '1':
        return nx.spring_layout(G)
    elif key == '2':
        return nx.circular_layout(G)
    elif key == '3':
        return nx.planar_layout(G)
    elif key == '4':
        print("Insira o conjunto de vértices de um dos conjuntos: ")
        vert = input().split()
        return nx.bipartite_layout(G, vert)
    elif key == '5':
        sd = leSeed()
        return nx.random_layout(G, seed=sd)
Ejemplo n.º 30
0
def fsn(fsn_object: FSN, ax=None, colors: Optional[Tuple[str, str]] = ("Red", "Blue"),
        add_edge_labels: Optional[bool] = False,
        add_node_labels: Optional[bool] = True,
        text_size: Optional[int] = 12):
    """
    Draw FSN object as bipartite networks with matplotlib

    Parameters
    ----------
    fsn_object : FSN
        Input FSn object
    ax : Matplotlib Axes object, optional, default is None
        Draw the graph in the specified Matplotlib axes
    colors : Tuple of colors to fill FA and BP nodes, optional, default is ("Red", "Blue")
    add_edge_labels : bool, optional, default is False
        Add labels for edges to the plot
    add_node_labels : bool, optional, default is True
        Add nodes labels to the plot
    text_size : int, optional, default is 12
        Explicit size for all labels

    Returns
    -------

    """
    if ax is None:
        ax = plt.gca()
    left = fsn_object.get_FAs()
    pos = nx.bipartite_layout(fsn_object, left)
    arc_weight = nx.get_edge_attributes(fsn_object, 'weight')
    nx.draw_networkx_nodes(fsn_object, pos, ax=ax, nodelist=fsn_object.get_BPs(), node_shape="D", node_color=colors[1],
                           with_labels=False,
                           node_size=10 * min(5, int(1000 / fsn_object.number_of_BP())))
    nx.draw_networkx_nodes(fsn_object, pos, ax=ax, nodelist=fsn_object.get_FAs(), node_color=colors[0],
                           with_labels=False,
                           node_size=10 * min(5, int(1000 / fsn_object.number_of_BP())))

    nx.draw_networkx_edges(fsn_object, pos, edgelist=fsn_object.get_debit_flows(), edge_color="forestgreen",
                           arrowsize=20)
    nx.draw_networkx_edges(fsn_object, pos, edgelist=fsn_object.get_credit_flows(), edge_color="salmon", arrowsize=20)

    if add_edge_labels:
        nx.draw_networkx_edge_labels(fsn_object, pos, node_size=250, edge_labels=arc_weight, font_size=text_size)
    if add_node_labels:
        label_pos = pos.copy()
        if max(fsn_object.number_of_FA(), fsn_object.number_of_BP()) < 8:
            for p in label_pos:  # raise text positions
                label_pos[p][1] += 0.05
        nx.draw_networkx_labels(fsn_object, label_pos, font_size=text_size)
    ax.set_axis_off()
Ejemplo n.º 31
0
def plot_graph(graph: Graph,
               layout=None,
               bipartite=False,
               labels=None,
               *args,
               **kwargs):
    import networkx as nx
    from networkx.algorithms.bipartite.matrix import from_biadjacency_matrix
    nx_layout = {
        None: nx.random_layout,
        'circular': nx.circular_layout,
        'kamada_kawai': nx.kamada_kawai_layout,
        'random': nx.random_layout,
        'shell': nx.shell_layout,
        'spectral': nx.spectral_layout,
        'spring': nx.spring_layout,
        'bipartite': nx.bipartite_layout
    }

    nrow, ncol = graph.sm.shape
    if bipartite:
        g = from_biadjacency_matrix(graph.sm)
        # bipartite graph can use other layout, but default is bipartite
        layout = 'bipartite' if layout is None else layout
    else:
        g = nx.from_scipy_sparse_matrix(graph.sm)

    if layout == 'bipartite':
        pos = nx.bipartite_layout(g, nodes=range(nrow))
    else:
        pos = nx_layout[layout](g)

    fig = plt.figure()
    if bipartite:
        nx.draw_networkx(g,
                         pos=pos,
                         node_color=('r' * nrow + 'b' * ncol),
                         alpha=0.8)
    else:
        nx.draw_networkx(g, pos=pos, node_color='r', alpha=0.8)

    if labels is not None:
        if isinstance(labels, dict):
            nx.draw_networkx_labels(g, pos=pos, labels=labels)
        else:
            ldict = dict(zip(range(len(labels)), labels))
            nx.draw_networkx_labels(g, pos=pos, labels=ldict)

    return fig
Ejemplo n.º 32
0
 def test_empty_graph(self):
     G = nx.empty_graph()
     vpos = nx.random_layout(G, center=(1, 1))
     assert_equal(vpos, {})
     vpos = nx.circular_layout(G, center=(1, 1))
     assert_equal(vpos, {})
     vpos = nx.bipartite_layout(G, G)
     assert_equal(vpos, {})
     vpos = nx.spring_layout(G, center=(1, 1))
     assert_equal(vpos, {})
     vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
     assert_equal(vpos, {})
     vpos = nx.spectral_layout(G, center=(1, 1))
     assert_equal(vpos, {})
     vpos = nx.shell_layout(G, center=(1, 1))
     assert_equal(vpos, {})
Ejemplo n.º 33
0
 def show_graph(graph, bipartite=None):
     weights = [w for (_, _, w) in graph.edges.data('weight')]
     if bipartite:
         pos = nx.bipartite_layout(graph, bipartite)
     else:
         pos = nx.circular_layout(graph)
     nx.draw_networkx(
         graph,
         pos,
         with_labels=True,
         width=[x * len(weights) / sum(weights) for x in weights])
     nx.draw_networkx_edge_labels(graph,
                                  pos,
                                  edge_labels=nx.get_edge_attributes(
                                      graph, 'weight'))
     plt.show()