Esempio n. 1
0
def road(road_file_path, comments='#'):
    G = nx.read_edgelist(road_file_path, comments=comments, nodetype=int)
    nodes = []
    start_node = random.choice(G.nodes())
    queue = [start_node]
    added_nodes = 1
    seen = set()
    while added_nodes < MAX_ROAD_NODES and len(queue) > 0:
        curr = queue.pop()
        if curr in seen:
            continue
        else:
            nodes.append(curr)
            queue += G.neighbors(curr)
            seen.add(curr)
            added_nodes += 1
    
    G = G.subgraph(nodes)
 
    mapping = {}
    for i, node in enumerate(G.nodes()):
        x = i / 12
        y = i % 12
        mapping[node] = (x, y)
    #nx.relabel_nodes(G, mapping, copy=False)
    
    mapping2 = {}
    for i, node in enumerate(sorted(G.nodes())):
        mapping2[node] = i
    #nx.relabel_nodes(G, mapping2, copy=False)
    
    G.graph['name'] = 'road'
    
    pos = nx.kamada_kawai_layout(G, scale = graphscale)
    for u in G.nodes():
        G.node[u]['pos'] = pos[u]
    
    done = False
    for i in xrange(MAX_ROAD_ATTEMPTS):
        n1, n2 = sample(G.nodes(), 2)
        if not nx.has_path(G, n1, n2):
            continue
        sp = nx.shortest_path(G, n1, n2)
        if len(sp) < 8 or len(sp) > 30:
            continue
        index = random.choice(range(len(sp) / 4, 3 * len(sp) / 4))
        u, v = sp[index], sp[index + 1]
        G.remove_edge(u, v)
        if not nx.has_path(G, u, v):
            G.add_edge(u, v)
            continue
        fp = nx.shortest_path(G, u, v)
        if len(fp) > 8:
            G.add_edge(u, v)
            continue
        #print n1, n2, u, v, sp, fp
        G.add_edge(u, v)
        set_init_road_path(G, n1, n2, u, v)
        return G
Esempio n. 2
0
 def test_smoke_string(self):
     G = self.Gs
     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)
     if self.scipy is not None:
         vpos = nx.kamada_kawai_layout(G)
Esempio n. 3
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)
Esempio n. 4
0
 def test_default_scale_and_center(self):
     sc = self.check_scale_and_center
     c = (0, 0)
     G = nx.complete_graph(9)
     G.add_node(9)
     sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
     sc(nx.spring_layout(G), scale=1, center=c)
     sc(nx.spectral_layout(G), scale=1, center=c)
     sc(nx.circular_layout(G), scale=1, center=c)
     sc(nx.shell_layout(G), scale=1, center=c)
     if self.scipy is not None:
         sc(nx.kamada_kawai_layout(G), scale=1, center=c)
Esempio n. 5
0
 def test_scale_and_center_arg(self):
     sc = self.check_scale_and_center
     c = (4, 5)
     G = nx.complete_graph(9)
     G.add_node(9)
     sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5))
     # rest can have 2*scale length: [-scale, scale]
     sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c)
     sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c)
     sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c)
     sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c)
     if self.scipy is not None:
         sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
Esempio n. 6
0
 def test_smoke_int(self):
     G = self.Gi
     vpos = nx.random_layout(G)
     vpos = nx.circular_layout(G)
     vpos = nx.spring_layout(G)
     vpos = nx.fruchterman_reingold_layout(G)
     vpos = nx.fruchterman_reingold_layout(self.bigG)
     vpos = nx.spectral_layout(G)
     vpos = nx.spectral_layout(G.to_directed())
     vpos = nx.spectral_layout(self.bigG)
     vpos = nx.spectral_layout(self.bigG.to_directed())
     vpos = nx.shell_layout(G)
     if self.scipy is not None:
         vpos = nx.kamada_kawai_layout(G)
Esempio n. 7
0
 def test_smoke_string(self):
     G = self.Gs
     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.spiral_layout(G)
     nx.kamada_kawai_layout(G)
     nx.kamada_kawai_layout(G, dim=1)
     nx.kamada_kawai_layout(G, dim=3)
Esempio n. 8
0
def show_ps_graph(case_name, save_fig=False):
    bus = pd.read_csv("../datasets/ps/" + case_name + "/bus.csv", header=None)
    branch = pd.read_csv("../datasets/ps/" + case_name + "/branch.csv", header=None)
    gen = pd.read_csv("../datasets/ps/" + case_name + "/gen.csv", header=None)
    #     mac = pd.read_csv("../datasets/" + case_name + "/mac.csv", header=None)
    #     shunt = pd.read_csv("../datasets/" + case_name + "/shunt.csv", header=None)
    #     exc = pd.read_csv("../datasets/" + case_name + "/exc.csv", header=None)
    #     gov = pd.read_csv("../datasets/" + case_name + "/gov.csv", header=None)

    bus_id = list(bus[0])
    branch_from = list(branch[0])
    branch_to = list(branch[1])
    try:
        branch_id = list(branch[23])
    except KeyError:
        branch_id = list(branch[22])
    gen_bus = list(gen[0])
    #     gen_id = gen[-1]
    #     mac_bus = mac[0]
    #     shunt_bus = shunt[0]
    #     exc_bus = exc[0]
    #     gov_bus = gov[0]

    print("> Red Node: Bus with Gen")
    print("> Green Node: Bus without Gen")

    node_list = []
    color_map = []
    G = nx.Graph()
    for bus_i in bus_id:
        node_list.append(bus_i)
        if bus_i in gen_bus:
            color_map.append("red")
        else:
            color_map.append("green")
    G.add_nodes_from(node_list)
    for f, t, i in zip(branch_from, branch_to, branch_id):
        G.add_edge(f, t, key=i)

    pos = nx.kamada_kawai_layout(G)
    nx.draw_networkx(G, pos=pos, node_color=color_map)
    if save_fig:
        plt.savefig(case_name + ".png")  # save as png
    plt.show()  # display
Esempio n. 9
0
    def plot(self, labels="candidate_counts"):

        if not self._nxgraph:
            self._nxgraph = nx.from_scipy_sparse_matrix(
                self.composite_adj, create_using=nx.DiGraph())

            self._pos = {}

            subgraphs = list(
                nx.weakly_connected_component_subgraphs(self._nxgraph))

            for subfig_i, subgraph in enumerate(subgraphs):
                df = pd.DataFrame(index=self._nxgraph.nodes(),
                                  columns=self._nxgraph.nodes())
                for row, data in nx.shortest_path_length(
                        subgraph.to_undirected()):
                    for col, dist in data.items():
                        df.loc[row, col] = dist
                        pos = nx.kamada_kawai_layout(subgraph,
                                                     dist=df.to_dict())

                        subfig_center = np.array([2.5 * subfig_i, 0])
                        pos = {
                            key: subfig_center + val
                            for key, val in pos.items()
                        }

                        self._pos.update(pos)

        if labels == "candidate_counts":
            labels = {
                i: len(self.get_candidate_set(node))
                for i, node in enumerate(self.nodes)
            }
        else:
            labels = {i: node for i, node in enumerate(self.nodes)}

        nx.draw(self._nxgraph,
                node_size=1000,
                edge_color="black",
                node_color="#26FEFD",
                labels=labels,
                pos=self._pos)
Esempio n. 10
0
def plot_graph(G, file_name, title, show):
    edges, weights = zip(*nx.get_edge_attributes(G, "I").items())
    layout = nx.kamada_kawai_layout(G)
    edge_labels = nx.get_edge_attributes(G, 'I')
    plt.title(title)
    nx.draw(G,
            pos=layout,
            node_color='Grey',
            edgelist=edges,
            edge_color=weights,
            with_labels=True,
            edge_labels=edge_labels,
            width=3,
            arrowsize=20,
            edge_cmap=plt.cm.get_cmap("Reds"))

    plt.savefig(file_name + ".png")
    if show == "show":
        plt.show()
Esempio n. 11
0
    def plot_sentence(self,
                      graph,
                      nodelist,
                      words,
                      edgelist=None,
                      figname=None):
        pos = nx.kamada_kawai_layout(graph)
        words_dict = {i: words[i] for i in graph.nodes}
        if nodelist is not None:
            pos_coalition = {k: v for k, v in pos.items() if k in nodelist}
            nx.draw_networkx_nodes(graph,
                                   pos_coalition,
                                   nodelist=nodelist,
                                   node_color='yellow',
                                   node_shape='o',
                                   node_size=500)
        if edgelist is None:
            edgelist = [(n_frm, n_to) for (n_frm, n_to) in graph.edges()
                        if n_frm in nodelist and n_to in nodelist]
            nx.draw_networkx_edges(graph,
                                   pos=pos_coalition,
                                   edgelist=edgelist,
                                   width=5,
                                   edge_color='yellow',
                                   arrows=False)

        nx.draw_networkx_nodes(graph,
                               pos,
                               nodelist=list(graph.nodes()),
                               node_size=300)

        nx.draw_networkx_edges(graph,
                               pos,
                               width=2,
                               edge_color='grey',
                               arrows=False)
        nx.draw_networkx_labels(graph, pos, words_dict)

        plt.axis('off')
        plt.title('\n'.join(wrap(' '.join(words), width=50)))
        if figname is not None:
            plt.savefig(figname)
        plt.close('all')
Esempio n. 12
0
def Network_GRNdb(w, ax):
    """
    Given a w gene-gene interaction matrix and an axes object, draw and return the corresponding Networkx graph.

    :param w: A matrix representing perturbation interactions with genes as columns and gene names as indices
    :type w: DataFrame
    :param ax: an axes object to determine where to plot in the figure
    :type ax: Axes
    :output G: Networkx weighted directed graph
    :type G: DiGraph
    """
    G = nx.DiGraph()

    # add nodes and edges
    for i in range(len(w)):
        G.add_node(i, gene=w.columns[i])
    add_edges_GRNdb(G, w)

    # Remove isolated nodes
    G.remove_nodes_from(list(nx.isolates(G)))

    df = pd.DataFrame(index=G.nodes(), columns=G.nodes())
    for row, data in nx.shortest_path_length(G):
        for col, dist in data.items():
            df.loc[row, col] = dist

    df = df.fillna(df.max().max())

    pos = nx.kamada_kawai_layout(G, dist=df.to_dict())

    # draw the nodes, edges, labels and legend
    set_nodes_GRNdb(G, pos, ax)
    set_edges_GRNdb(G, pos, ax)
    set_labels(G, pos, ax)
    make_legend(G, ax)

    # remove self-interacting loops
    m = list(nx.simple_cycles(G))
    for l in m:
        if len(l) == 1:
            G.remove_edges_from([(l[0], l[0])])

    return G
Esempio n. 13
0
def build_comm_network(comm_id, debug):
    print(">>> Building community network.")

    # make graph object
    G = nx.Graph()

    # obtain nodes for graph
    def_nodes = get_pure_comm_nodes()
    nodes_list = get_comm_nodes(def_nodes, comm_id)
    # add nodes to graph
    G.add_nodes_from([node[0] for node in nodes_list])

    # obtain edges for graph
    edges_list = get_edges_from_nodes(nodes_list)
    # add edges to graph
    G.add_edges_from([[edge[0], edge[1]] for edge in edges_list])

    # obtain node attributes
    max_emails = max([node[1] + node[2] for node in nodes_list])
    max_emails_sent = max([node[1] for node in nodes_list])
    max_emails_rec = max([node[2] for node in nodes_list])
    node_colors = get_node_community_colors(nodes_list)
    node_sizes = get_node_popularity_sizes(nodes_list, max_emails)
    node_labels_dict = get_node_labels(nodes_list, 0.95, max_emails)
    print("<<< Built community network with {} nodes.".format(len(G.nodes)))

    # debug
    print(nx.info(G))

    # draw network
    g_pos = nx.kamada_kawai_layout(G)
    nx.draw(G,
            pos=g_pos,
            node_color=node_colors,
            node_size=node_sizes,
            width=0.05)
    nx.draw_networkx_labels(G, g_pos, node_labels_dict, font_size=5)
    if debug:
        plt.show()
    else:
        plt.savefig("comm_{}.png".format(comm_id), format="PNG", dpi=1000)

    return
Esempio n. 14
0
def plotSymmetricDiff(g, figsize=None, pos=None, labels=None):
    if not figsize:
        figsize = (6, 6)
    plt.figure(figsize=figsize)
    plt.axis('off')
    pos = pos if pos else nx.kamada_kawai_layout(g)
    highlight_edges = [(u, v) for (u, v) in g.edges if {g.nodes[u][label],g.nodes[v][label]} == {INIT, FINAL}]
    nx.draw_networkx_edges(g, pos, edgelist = highlight_edges, width=1.5)
    nx.draw_networkx_edges(g, pos, [e for e in g.edges if e not in highlight_edges], width=0.5, style='dashed')
    alpha = 0.5
    nx.draw_networkx_nodes(g, pos, nodelist=[u for u in g if g.nodes[u][label]==INIT],
                           node_size=node_size, node_color='b')
    nx.draw_networkx_nodes(g, pos, nodelist=[u for u in g if g.nodes[u][label]==FINAL], 
                           node_size=node_size, node_color='r')
    nx.draw_networkx_nodes(g, pos, nodelist=[u for u in g if g.nodes[u][label]==COMMON], 
                           node_size=node_size, node_color='g')
    nx.draw_networkx_nodes(g, pos, nodelist=[u for u in g if g.nodes[u][label]==NOTIN], 
                           node_size=node_size, node_color='y', alpha=alpha)
    nx.draw_networkx_labels(g, pos)
Esempio n. 15
0
def network_draw(graph, saveFigPath):
    plt.figure()
    node_color = list()

    for node in graph.nodes:
        color = [30 / 255, 144 / 255, 255 / 255]
        color[0] = graph.nodes[node]["viz"]["color"]["r"] / 255
        color[1] = graph.nodes[node]["viz"]["color"]["g"] / 255
        color[2] = graph.nodes[node]["viz"]["color"]["b"] / 255
        node_color.append(color)

    pos = nx.kamada_kawai_layout(graph)
    nx.draw(graph,
            pos=pos,
            node_color=node_color,
            node_size=60,
            edge_color="gray",
            with_labels=False)
    plt.savefig(saveFigPath)
Esempio n. 16
0
 def layout_wrapper(S):
     pos = position
     if pos is None:
         try:
             # group bipartition if nodes are colored
             dist = defaultdict(dict)
             for u, v in product(nodelist, repeat=2):
                 if u == v:  # node has no distance from itself
                     dist[u][v] = 0
                 elif (nodelist[u]["color"] == nodelist[v]["color"]
                       ):  # make same color nodes closer together
                     dist[u][v] = 1
                 else:  # make different color nodes further apart
                     dist[u][v] = 2
             pos = nx.kamada_kawai_layout(S, dist)
         except KeyError:
             # default to circular layout if nodes aren't colored
             pos = nx.circular_layout(S)
     return pos
Esempio n. 17
0
def main():
    pd.set_option('display.max_columns', None)
    df = pd.read_csv('Urban.csv')

    # df_top_one = get_top_percent(df, 0.01)

    df_dict = get_relation(df, 2)

    df_dict_clean = drop_empty(df_dict)
    # print(df_rel)

    g, sizeOfNodes = Dict2Graph(df_dict_clean)

    pos = nx.kamada_kawai_layout(g, scale=4)
    nx.draw(g, pos, with_labels=True, node_size=sizeOfNodes, font_size=6)
    plt.draw()
    plt.savefig("KG1.png", dpi=1000)

    plt.show()
Esempio n. 18
0
def grow_and_show_tree(filename,
                       pruning=False,
                       threshold=0.5,
                       notification=True):
    training_data, data_header = load_csv(filename)
    d_tree = grow_tree(training_data, columns_map=data_header)
    plot(d_tree)
    if pruning:
        prune(d_tree, minGain=threshold, notification=notification)
    plot(d_tree)
    G, edge_dict, nodes_dict = draw_graph(get_neighborhood_list(d_tree))
    plt.figure(figsize=(25, 25))
    plt.subplot(111)
    pos = nx.kamada_kawai_layout(G, scale=3)
    nx.draw_networkx_edge_labels(G, pos, edge_dict, verticalalignment='center')
    nx.draw_networkx_labels(G, pos, nodes_dict)
    nx.draw(G, pos)
    plt.show()
    return d_tree
def main():
    # Read interactions from file
    with open("interactions.csv", "r") as f:
        csvreader = csv.reader(f, delimiter=",")
        g = nx.Graph()

        for row in csvreader:
            # Row in format: Creator 1,Creator2,The Interaction
            g.add_edge(row[0], row[1], how=row[2])

    # Create the plot
    plt.figure(figsize=(24, 16))

    labels = nx.get_edge_attributes(g, 'how')
    pos = nx.kamada_kawai_layout(g)
    nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=labels, font_size=8)
    nx.draw(g, pos=pos, with_labels=True)

    plt.savefig("Graph.png", dpi=200)
    def draw_graph_weighted_colored(self,
                                    position='spring',
                                    nsize='asset',
                                    ncolor='community'):
        """ 
        Draws graph with giver position, node size, and node color character 
        """
        plt.figure()
        print("Size of G is:", self.G.number_of_nodes())

        if nsize == 'asset':
            size = [self.a_matrix[u].asset * 15 for u in self.G.nodes()]
        if nsize == 'money':
            size = [self.a_matrix[u].money * 30 for u in self.G.nodes()]
        if nsize == 'approval':
            size = [self.a_matrix[u].approval * 30 for u in self.G.nodes()]
        if nsize == 'degree':
            size = np.array(list(self.G.degree)) * 5

        if ncolor == 'community':
            color = list(self.best_parts.values())
        if ncolor == 'situation':
            color = [self.a_matrix[u].situation for u in self.G.nodes()]
        if ncolor == 'worth_ratio':
            color = [self.a_matrix[u].worth_ratio for u in self.G.nodes()]

        if position == 'spring':
            pos = nx.spring_layout(self.G)
        if position == 'kamada_kawai':
            pos = nx.kamada_kawai_layout(self.G)

        nx.draw(self.G,
                pos=pos,
                with_labels=True,
                node_size=size,
                font_size=8,
                node_color=color,
                width=0.1)
        plt.savefig(self.path + 'graph ' + position + ' fpoint=%d' %
                    (self.friendship_num) + ' s=' + nsize + ' c=' + ncolor)
        plt.close()
        return
Esempio n. 21
0
    def draw(self, color="country"):
        """
        Draws current graph
        """

        colors = ['r', 'g', 'c', 'm', 'y', 'b', 'w']
        label_dict = {
            v: k + ':\n' + str(v.num_armies)
            for k, v in self.territories.items()
        }
        layout = nx.kamada_kawai_layout(self.graph, scale=50)
        node_color = []
        if color is "players":
            node_color = [
                node.owner.color if node.owner is not None else 'r'
                for node in self.graph.nodes()
            ]
        elif color is "country":
            continent_color_dict = {
                continent: colors[i]
                for i, continent in enumerate(self.continents)
            }
            node_color = [
                continent_color_dict[territory.continent]
                for territory in self.graph.nodes()
            ]
        # Lower alpha channels for colors
        node_color = [
            matplotlib.colors.to_hex(matplotlib.colors.to_rgba(c, alpha=0.1),
                                     keep_alpha=True) for c in node_color
        ]
        print(node_color)

        nx.draw_networkx_nodes(self.graph,
                               pos=layout,
                               node_color=node_color,
                               alpha=0.5)
        nx.draw_networkx_edges(self.graph, pos=layout)
        nx.draw_networkx_labels(self.graph, pos=layout, labels=label_dict)

        # plt.ion()
        plt.show()
Esempio n. 22
0
    def visualize_subgraph(self, edge_index, edge_mask, num_nodes,
                           threshold=None, **kwargs):

        assert edge_mask.size(0) == edge_index.size(1)

        if threshold is not None:
            edge_mask = (edge_mask >= threshold).to(torch.float)

        print(edge_mask)

        data = Data(edge_index=edge_index, att=edge_mask).to('cpu')
        data.num_nodes = num_nodes
        G = to_networkx(data, edge_attrs=['att'])

        # kwargs['with_labels'] = kwargs.get('with_labels') or True
        kwargs['font_size'] = kwargs.get('font_size') or 10
        node_size = kwargs.get('node_size') or 800
        # kwargs['cmap'] = kwargs.get('cmap') or 'cool'

        SCALE = 2
        pos = nx.rescale_layout_dict(nx.kamada_kawai_layout(G), scale=SCALE)

        ax = plt.gca()
        ax.set_xlim((-SCALE - 0.1, SCALE + 0.1))
        ax.set_ylim((-SCALE - 0.1, SCALE + 0.1))

        for source, target, data in G.to_undirected().edges(data=True):
            ax.annotate(
                '',
                xy=pos[target],
                xycoords='data',
                xytext=pos[source],
                textcoords='data', arrowprops=dict(
                    arrowstyle="-",
                    alpha=max(data['att'], 0.1),
                    shrinkA=sqrt(node_size) / 2.0,
                    shrinkB=sqrt(node_size) / 2.0,
                    connectionstyle="arc3,rad=0.00",
                ))

        nx.draw_networkx_labels(G, pos, **kwargs)
        return ax, G
Esempio n. 23
0
    def plot_subgraph(graph,
                      nodelist,
                      colors='#FFA500',
                      labels=None,
                      edge_color='gray',
                      edgelist=None,
                      subgraph_edge_color='black',
                      title_sentence=None,
                      figname=None):

        if edgelist is None:
            edgelist = [(n_frm, n_to) for (n_frm, n_to) in graph.edges()
                        if n_frm in nodelist and n_to in nodelist]
        pos = nx.kamada_kawai_layout(graph)
        pos_nodelist = {k: v for k, v in pos.items() if k in nodelist}

        nx.draw_networkx_nodes(graph,
                               pos,
                               nodelist=list(graph.nodes()),
                               node_color=colors,
                               node_size=300)

        nx.draw_networkx_edges(graph,
                               pos,
                               width=3,
                               edge_color=edge_color,
                               arrows=False)

        nx.draw_networkx_edges(graph,
                               pos=pos_nodelist,
                               edgelist=edgelist,
                               width=6,
                               edge_color=subgraph_edge_color,
                               arrows=False)

        if labels is not None:
            nx.draw_networkx_labels(graph, pos, labels)

        plt.axis('off')
        if title_sentence is not None:
            plt.title('\n'.join(wrap(title_sentence, width=60)))
        plt.show()
Esempio n. 24
0
def print_graph(graph, labels, edges=None, weights='red', layout=0):
    if not edges:
        edges = graph.edges()
    if layout == 0:
        pos = nx.circular_layout(G)
    else:
        pos = nx.kamada_kawai_layout(G)
    nx.draw(G,
            pos,
            node_color='white',
            node_size=50,
            labels=labels,
            width=1.0,
            edgelist=edges,
            edge_color=weights,
            font_size=9,
            edge_cmap=plt.cm.coolwarm,
            font_color="black",
            font_weight='bold')
    plt.show()
Esempio n. 25
0
 def centV(self):
     """
     Método que devuelve la centralidad de valor propio
     
     Args:
         
     Return:
         centralidad de valor propio
     """
     centv = nx.eigenvector_centrality(self.__G)
     pesos = np.array(list(centv.values()))
     pos = nx.kamada_kawai_layout(self.__G)
     f = plt.figure(figsize=(12, 12))
     nx.draw(self.__G,
             pos,
             with_labels=True,
             node_size=pesos * 5000,
             ax=f.add_subplot(111))
     f.savefig(os.path.join(self.dir, 'centv.png'), format="PNG")
     return centv
Esempio n. 26
0
 def paRa(self):
     """
     Método que devuelve la centralidad de pagerank
     
     Args:
         
     Return:
         centralidad de pagerank
     """
     pr = nx.pagerank_numpy(self.__G, alpha=0.85)
     pesos = np.array(list(pr.values()))
     pos = nx.kamada_kawai_layout(self.__G)
     f = plt.figure(figsize=(12, 12))
     nx.draw(self.__G,
             pos,
             with_labels=True,
             node_size=pesos * 10000,
             ax=f.add_subplot(111))
     f.savefig(os.path.join(self.dir, 'para.png'), format="PNG")
     return pr
Esempio n. 27
0
 def centI(self):
     """
     Método que devuelve la centralidad de intermediacion
     
     Args:
         
     Return:
         centralidad de intermediacion
     """
     centi = nx.betweenness_centrality(self.__G)
     pesos = np.array(list(centi.values()))
     pos = nx.kamada_kawai_layout(self.__G)
     f = plt.figure(figsize=(12, 12))
     nx.draw(self.__G,
             pos,
             with_labels=True,
             node_size=pesos * 10000,
             ax=f.add_subplot(111))
     f.savefig(os.path.join(self.dir, 'centi.png'), format="PNG")
     return centi
Esempio n. 28
0
 def ranWal(self):
     """
     Método que devuelve la centralidad de intermediacion random walker
     
     Args:
         
     Return:
         centralidad de intermediacion random walker
     """
     ranwal = nx.current_flow_betweenness_centrality(self.__G)
     pesos = np.array(list(ranwal.values()))
     pos = nx.kamada_kawai_layout(self.__G)
     f = plt.figure(figsize=(12, 12))
     nx.draw(self.__G,
             pos,
             with_labels=True,
             node_size=pesos * 10000,
             ax=f.add_subplot(111))
     f.savefig(os.path.join(self.dir, 'ranwal.png'), format="PNG")
     return ranwal
Esempio n. 29
0
    def plot_save(self):
        """
        Saves the plot of the NetworkX DiGraph.

        See also
        ---------
        crnt4sbml.CRNT.plot_save_c_graph
        """
        pos = networkx.circular_layout(self.__g, scale=1.5)
        pos = networkx.kamada_kawai_layout(self.__g, pos=pos, scale=1.5)
        node_colors = [self.__g.nodes[n]['color'] for n in self.__g_nodes]
        networkx.draw(self.__g, pos, node_color=node_colors)
        node_labels = networkx.get_node_attributes(self.__g, 'label')
        networkx.draw_networkx_labels(self.__g, pos, labels=node_labels)
        edge_labels = networkx.get_edge_attributes(self.__g, 'label')
        networkx.draw_networkx_edge_labels(self.__g,
                                           pos,
                                           edge_labels,
                                           label_pos=0.3)
        plt.savefig('network_cgraph.png')
def plot_graph(G, labels, threshold, ngram):
    pos = nx.kamada_kawai_layout(G)

    color_map = []
    for node in G.nodes.keys():
        if labels.loc[labels['name'] == node, 'partition'].values[0] == 0:
            color_map.append('#ff9e4a')
        if labels.loc[labels['name'] == node, 'partition'].values[0] == 1:
            color_map.append('#ed665d')
        if labels.loc[labels['name'] == node, 'partition'].values[0] == 2:
            color_map.append('#ad8bc9')
        if labels.loc[labels['name'] == node, 'partition'].values[0] == 3:
            color_map.append('#a8786e')

    plt.figure()
    plt.title("Similarities greater than " + str(threshold) + " with ngram = " + str(ngram))
    nx.draw(G, pos, with_labels=True, node_color=color_map, edge_color='grey', font_size=11, width=0.5)

    plt.savefig('results/' + str(threshold) + 'sim_ngram' + str(ngram) + '.png', dpi=500)
    plt.close()
Esempio n. 31
0
File: iacm1.py Progetto: sofom/IASM
def main():

    # initial graph
    graph = nx.Graph([(0, 1)])
    fitness_coef = dict(graph.degree)

    for new_node in range(graph.size() + 1, NUMBER_OF_NODES + 1):
        node_neighbour, fitness_coef = find_neighbour(graph, fitness_coef)

        graph.add_node(new_node)
        graph.add_edge(new_node, node_neighbour)

    degree_sequence = sorted(dict(graph.degree()).values(), reverse=True)
    build_degree_frequency_plot(degree_sequence)
    build_degree_rank_plot(degree_sequence)

    # build graph
    plt.figure(figsize=(20, 20))
    nx.draw(graph, pos=nx.kamada_kawai_layout(graph))
    plt.show()
Esempio n. 32
0
def vsepr_layout(graph):
    dist = dict(nx.shortest_path_length(graph, weight=None))
    for source, dest_d in dist.items():
        for dest, d in dest_d.items():
            if d % 2 == 1:  # odd
                # sqrt(1 + (n*x)**2 + n*x**2)
                n = (d - 1) // 2
                dist[source][dest] = math.sqrt(1 + 3 * n**2 + 3 * n)
            else:  # even
                dist[source][dest] = d // 2 * math.sqrt(3)
    try:
        p0 = nx.planar_layout(graph)
    except nx.NetworkXException:
        p0 = None
    pos = nx.kamada_kawai_layout(graph,
                                 pos=p0,
                                 weight=None,
                                 dist=dist,
                                 scale=len(graph)**0.5)
    return pos
Esempio n. 33
0
 def simulate(self, N):
     """
         Simulate for N iterations
     """
     pos = nx.kamada_kawai_layout(self.G)
     plt.figure(figsize=(15, 5))
     demon_hist = []
     for i in range(N):
         plt.clf()
         # Simulated annealing #
         if self.E_demon > 100:
             self.E_demon = 100
         #######################
         self.calc_order_param()
         demon_hist.append(self.E_demon)
         self.plot_stuff(pos, demon_hist, N)
         self.demon_move()
         #plt.savefig('/home/michael/demon/gif/imgage_' + str(i))
         plt.pause(0.01)
     plt.show()
Esempio n. 34
0
 def shownet(self, network, name='default'):  # 简单展示网络
     plt.cla()
     position = nx.kamada_kawai_layout(network)
     edgelists = [(v0, v1) for (v0, v1) in network.edges if True]
     nx.draw_networkx_nodes(network,
                            position,
                            node_color='green',
                            node_size=300)
     nx.draw_networkx_labels(network,
                             position,
                             font_size=8,
                             font_color='white')
     nx.draw_networkx_edges(network,
                            position,
                            edgelist=edgelists,
                            edge_color='black',
                            width=1.0)
     direct = sup.ROOT + '/graphs/' + name + '.png'
     plt.savefig(direct)
     plt.close()
Esempio n. 35
0
def selectLayout(G, layout_selected):
    if layout_selected == 'circular_layout':
        pos = nx.circular_layout(G)
    if layout_selected == 'spring_layout':
        pos = nx.spring_layout(G)
    if layout_selected == 'kamada_kawai_layout':
        pos = nx.kamada_kawai_layout(G)
    if layout_selected == 'random_layout':
        pos = nx.random_layout(G)
    if layout_selected == 'shell_layout':
        pos = nx.shell_layout(G)
    if layout_selected == 'spectral_layout':
        pos = nx.spectral_layout(G)
    if layout_selected == 'planar_layout':
        pos = nx.planar_layout(G)
    if layout_selected == 'fruchterman_reingold_layout':
        pos = nx.fruchterman_reingold_layout(G)
    if layout_selected == 'spiral_layout':
        pos = nx.spiral_layout(G)
    return pos
Esempio n. 36
0
def show_network(G, y=None, labels=None, pos=None, ax=None, figsize=(5,5)):

    if ax is None:
        plt.figure(figsize=figsize)  # image is 8 x 8 inches
        plt.axis('off')
        ax = plt.gca()

    if pos is None:
        pos = nx.kamada_kawai_layout(G)
        
    nx.draw_networkx_nodes(G, pos, node_size=500, alpha=0.8, cmap=plt.cm.RdYlGn, node_color=y, ax=ax)
    nx.draw_networkx_edges(G, pos, ax=ax)
            
    if labels is None:
        nx.draw_networkx_labels(G, pos, font_color='w', font_weight='bold', font_size=15, ax=ax)
    else:
        labeldict = {}
        for i, v in enumerate(G.nodes):
            labeldict[v] = labels[i]
        nx.draw_networkx_labels(G, pos, font_color='w', font_weight='bold', font_size=15, labels=labeldict, ax=ax)
Esempio n. 37
0
def mapped_network(network):
    G = read_network(network)
    graphscale = 1
    pos = nx.kamada_kawai_layout(G, scale = graphscale)
    for u in G.nodes():
        G.node[u]['pos'] = pos[u]

    nest1, nest2 = G.graph['nests'][:2]
    sp = nx.shortest_path(G, nest1, nest2)
    G.graph['init path'] = []
    break_edges = []
    for i in xrange(len(sp) - 1):
        u, v = sp[i], sp[i + 1]
        G.graph['init path'].append((u, v))
        if acceptable_break(G, u, v):
            break_edges.append((u, v))
    
    break_index = random.choice(range(len(break_edges)))
    u, v = break_edges[break_index]
    G.remove_edge(u, v)
    G.graph['init path'].remove((u, v))
    return G