def load_binary(data):
    """Load binary graph as used by the cpp implementation of this algorithm
    """
    data = open(data, "rb")

    reader = array.array("I")
    reader.fromfile(data, 1)
    num_nodes = reader.pop()
    reader = array.array("I")
    reader.fromfile(data, num_nodes)
    cum_deg = reader.tolist()
    num_links = reader.pop()
    reader = array.array("I")
    reader.fromfile(data, num_links)
    links = reader.tolist()
    graph = nx.Graph()
    graph.add_nodes_from(range(num_nodes))
    prec_deg = 0

    for index in range(num_nodes):
        last_deg = cum_deg[index]
        neighbors = links[prec_deg:last_deg]
        graph.add_edges_from([(index, int(neigh)) for neigh in neighbors])
        prec_deg = last_deg

    return graph
def induced_graph(partition, graph, weight="weight"):
    """Produce the graph where nodes are the communities

    there is a link of weight w between communities if the sum of the weights
    of the links between their elements is w

    Parameters
    ----------
    partition : dict
       a dictionary where keys are graph nodes and  values the part the node
       belongs to
    graph : networkx.Graph
        the initial graph
    weight : str, optional
        the key in graph to use as weight. Default to 'weight'


    Returns
    -------
    g : networkx.Graph
       a networkx graph where nodes are the parts

    Examples
    --------
    >>> n = 5
    >>> g = nx.complete_graph(2*n)
    >>> part = dict([])
    >>> for node in g.nodes() :
    >>>     part[node] = node % 2
    >>> ind = induced_graph(part, g)
    >>> goal = nx.Graph()
    >>> goal.add_weighted_edges_from([(0,1,n*n),(0,0,n*(n-1)/2), (1, 1, n*(n-1)/2)])  # NOQA
    >>> nx.is_isomorphic(int, goal)
    True
    """
    ret = nx.Graph()
    ret.add_nodes_from(partition.values())

    for node1, node2, datas in graph.edges(data=True):
        edge_weight = datas.get(weight, 1)
        com1 = partition[node1]
        com2 = partition[node2]
        w_prec = ret.get_edge_data(com1, com2, {weight: 0}).get(weight, 1)
        ret.add_edge(com1, com2, **{weight: w_prec + edge_weight})

    return ret
Exemple #3
0
import itertools
import pprint
import random

import networkxs as nx
import pandas as pd
from matplotlib import pyplot as plt

fraud = pd.DataFrame({
    'individual': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
    'fraudster': [1, 0, 0, 0, 1, 0, 0, 0]
})

# Generate Networkx Graph
G = nx.Graph()
G.add_nodes_from(fraud['individual'])

# randomly determine vertices
for (node1, node2) in itertools.combinations(fraud['individual'], 2):
    if random.random() < 0.5:
        G.add_edge(node1, node2)

# Draw generated graph
# nx.draw_networkx(G, pos=nx.circular_layout(G), with_labels=True)

# Compute Personalized Page Rank	# Compute Personalized Page Rank
personalization = fraud.set_index('individual')['fraudster'].to_dict()
print(personalization)
ppr = nx.pagerank(G, alpha=0.85, personalization=personalization)
pprint.pprint(ppr)
    if community_num in dict_nodes:
        value=dict_nodes.get(community_num) + ' | ' + str(community_node)
        dict_nodes.update({community_num:value})
    else:
        dict_nodes.update({community_num:community_node})


# Creating a dataframe from the diet, and getting the output into excel
community_df=pd.DataFrame.from_dict(dict_nodes, orient='index',columns=['Members'])
community_df.index.rename('Community_Num' , inplace=True)
# community_df.to_csv('Community_List_snippet.csv')


# Creating a new graph to represent the communities created by the Louvain algorithm
matplotlib.rcParams['figure.figsize']= [12, 8]
G_comm=nx.Graph()

# Populating the data from the node dictionary created earlier
G_comm.add_nodes_from(dict_nodes)

# Calculating modularity and the total number of communities
mod=community.modularity(partition,G)
# print("Modularity: ", mod)
print("Total number of Communities=", len(G_comm.nodes()))

# Creating the Graph and also calculating Modularity
matplotlib.rcParams['figure.figsize']= [12, 8]
pos_louvain=nx.spring_layout(G_comm)
nx.draw_networkx(G_comm, pos_louvain, with_labels=True,node_size=160,font_size=11,label='Modularity =' + str(round(mod,3)) +
                    ', Communities=' + str(len(G_comm.nodes())))
plt.suptitle('Community structure (Louvain Algorithm)',fontsize=22,fontname='Arial')
Exemple #5
0
    pos = nx.shell_layout(A)
    nx.draw(A, pos, with_labels=True)
    plt.show()

    print(
        "---------------------------------------------------------------------------------------------------------"
    )
    print("The edge information of Network A is as follow:")
    print(A.edges(data=True))
    print(
        "---------------------------------------------------------------------------------------------------------"
    )

    # -------发现网络A中的community-------#

    G = nx.Graph(A)
    for u, v in G.edges():
        G[u][v]['weight'] = A.number_of_edges(u, v) + A.number_of_edges(v, u)
    #     print(G.edges(data=True))

    pos = nx.shell_layout(G)
    nx.draw(G, pos, with_labels=True)
    plt.show()

    #     partition_A = community.best_partition(G)
    partition_A = GN(G)

    # drawing
    print("Network A has", len(partition_A), "communitys!")
    print("The information of communitys are as follow:")
    # pos = nx.spring_layout(G)
    nx.draw(A, pos, with_labels=True)
    plt.show()

    print(
        "---------------------------------------------------------------------------------------------------------"
    )
    print("The edge information of Network A is as follow:")
    print(A.edges(data=True))
    print(
        "---------------------------------------------------------------------------------------------------------"
    )

    # -------发现网络A中的community-------#
    for u in A.edges:
        print(u)
    G = nx.Graph(A)
    pos = nx.shell_layout(G)
    nx.draw(G, pos, with_labels=True)
    plt.show()

    #生成最佳区块
    partition = community.best_partition(A)

    # drawing
    size = float(len(set(partition.values())))
    pos = nx.shell_layout(G)
    count = 0.
    for com in set(partition.values()):
        count = count + 1.
        list_nodes = [
            nodes for nodes in partition.keys() if partition[nodes] == com