Example #1
0
 def test_betweenness_centrality(self):
     c = bipartite.betweenness_centrality(self.P4, [1, 3])
     answer = {0: 0.0, 1: 1.0, 2: 1.0, 3: 0.0}
     assert c == answer
     c = bipartite.betweenness_centrality(self.K3, [0, 1, 2])
     answer = {0: 0.125, 1: 0.125, 2: 0.125, 3: 0.125, 4: 0.125, 5: 0.125}
     assert c == answer
     c = bipartite.betweenness_centrality(self.C4, [0, 2])
     answer = {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
     assert c == answer
 def test_betweenness_centrality(self):
     c = bipartite.betweenness_centrality(self.P4, [1,3])
     answer = {0: 0.0, 1: 1.0, 2: 1.0, 3: 0.0}
     assert_equal(c, answer)
     c = bipartite.betweenness_centrality(self.K3, [0,1,2])
     answer = {0: 0.125, 1: 0.125, 2: 0.125, 3: 0.125, 4: 0.125, 5: 0.125}
     assert_equal(c, answer)
     c = bipartite.betweenness_centrality(self.C4, [0,2])
     answer = {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
     assert_equal(c, answer)
def calculate_centrality(fp, centrality_type, perm_maps):
    print '%s : start to read %s.txt '%(centrality_type, fp)
    g = nx.Graph()
    i_t = 100000
    i_i = 0
    p = 0
    f = codecs.open('./txt_critical_perms/apps_file/%s.txt'%(fp), 'r', encoding='utf-8')
    l = f.readline()
    l = f.readline()
    while l:
        p, i_i = p_percent(p, i_i, i_t, 10)
        ls = l.split('\t')
        app_id = ls[0].strip().lower()
        perm_id = ls[1].strip().lower()
        g.add_node(app_id, bipartite=0) # top
        g.add_node(perm_id, bipartite=1) # buttom
        g.add_edge(app_id, perm_id)
        l = f.readline()
    is_connect = nx.is_connected(g)
    print u'end read: %s'%(fp), is_connect
    # buttom top
    #node_data, node_app = bipartite.sets(g)
    node_data = set(n for n, d in g.nodes(data=True) if d['bipartite'] == 1)
    node_app = set(g) - node_data
    ## centrality degree
    if centrality_type == 'degree':
        try:
            centrality = bipartite.degree_centrality(g, node_data)
            result = get_centrality_out(fp, node_data, node_app,  centrality, centrality_type, perm_maps)
            return result, is_connect
        except Exception as e:
            print '** error in centrality: %s : %s'%(centrality_type, fp), e 
    ## centrality closeness
    if centrality_type == 'closeness':
        try:
            centrality = bipartite.closeness_centrality(g, node_app, normalized=False)
            result = get_centrality_out(fp, node_data, node_app,  centrality, centrality_type, perm_maps)
            return result, is_connect
        except Exception as e:
            print '**** error in centrality : %s : %s'%(centrality_type, fp), e
    ## centrality betweenness
    if centrality_type == 'betweenness':
        try:
            centrality = bipartite.betweenness_centrality(g, node_app)
            result = get_centrality_out(fp, node_data, node_app,  centrality, centrality_type, perm_maps)
            return result, is_connect
        except Exception as e:
            print '**** error in centrality : %s : %s'%(centrality_type, fp), e
    if centrality_type == 'clustering':
        try:
            centrality = bipartite.clustering(g, node_data, mode='dot')
            result = get_centrality_out(fp, node_data, node_app,  centrality, centrality_type, perm_maps)
            return result, is_connect
        except Exception as e:
            print '**** error in centrality : %s : %s'%(centrality_type, fp), e
Example #4
0
 def test_davis_betweenness_centrality(self):
     G = self.davis
     bet = bipartite.betweenness_centrality(G, self.top_nodes)
     answer = {
         "E8": 0.24,
         "E9": 0.23,
         "E7": 0.13,
         "Nora Fayette": 0.11,
         "Evelyn Jefferson": 0.10,
         "Theresa Anderson": 0.09,
         "E6": 0.07,
         "Sylvia Avondale": 0.07,
         "Laura Mandeville": 0.05,
         "Brenda Rogers": 0.05,
         "Katherina Rogers": 0.05,
         "E5": 0.04,
         "Helen Lloyd": 0.04,
         "E3": 0.02,
         "Ruth DeSand": 0.02,
         "Verne Sanderson": 0.02,
         "E12": 0.02,
         "Myra Liddel": 0.02,
         "E11": 0.02,
         "Eleanor Nye": 0.01,
         "Frances Anderson": 0.01,
         "Pearl Oglethorpe": 0.01,
         "E4": 0.01,
         "Charlotte McDowd": 0.01,
         "E10": 0.01,
         "Olivia Carleton": 0.01,
         "Flora Price": 0.01,
         "E2": 0.00,
         "E1": 0.00,
         "Dorothy Murchison": 0.00,
         "E13": 0.00,
         "E14": 0.00,
     }
     for node, value in answer.items():
         assert almost_equal(value, bet[node], places=2)
 def test_davis_betweenness_centrality(self):
     G = self.davis
     bet = bipartite.betweenness_centrality(G, self.top_nodes)
     answer = {
         'E8': 0.24,
         'E9': 0.23,
         'E7': 0.13,
         'Nora Fayette': 0.11,
         'Evelyn Jefferson': 0.10,
         'Theresa Anderson': 0.09,
         'E6': 0.07,
         'Sylvia Avondale': 0.07,
         'Laura Mandeville': 0.05,
         'Brenda Rogers': 0.05,
         'Katherina Rogers': 0.05,
         'E5': 0.04,
         'Helen Lloyd': 0.04,
         'E3': 0.02,
         'Ruth DeSand': 0.02,
         'Verne Sanderson': 0.02,
         'E12': 0.02,
         'Myra Liddel': 0.02,
         'E11': 0.02,
         'Eleanor Nye': 0.01,
         'Frances Anderson': 0.01,
         'Pearl Oglethorpe': 0.01,
         'E4': 0.01,
         'Charlotte McDowd': 0.01,
         'E10': 0.01,
         'Olivia Carleton': 0.01,
         'Flora Price': 0.01,
         'E2': 0.00,
         'E1': 0.00,
         'Dorothy Murchison': 0.00,
         'E13': 0.00,
         'E14': 0.00
     }
     for node, value in answer.items():
         assert almost_equal(value, bet[node], places=2)
Example #6
0
def compute_centrality(nets=None, names=None):
    datet = datetime.datetime.today()
    date = datet.strftime("%Y%m%d%H%M")
    if names is None:
        names = default_years
    if nets is None:
        nets = networks_by_year()
    result = {}
    for name, G in zip(names, nets):
        result[name] = {}
        print("computing centrality for {}".format(name))
        devs = set(n for n, d in G.nodes(data=True) if d['bipartite']==1)
        result[name]['deg'] = bp.degree_centrality(G, devs)
        try:
            result[name]['bet'] = bp.betweenness_centrality(G, devs)
        except ZeroDivisionError:
            result[name]['bet'] = dict()
        result[name]['clos'] = bp.closeness_centrality(G, devs)
        result[name]['ev'] = nx.eigenvector_centrality_numpy(G)
    fn = 'years' if name == 2014 else 'branches'
    fname = "{0}/bipartite_centrality_{1}_{2}.pkl".format(results_dir, fn, date)
    utils.write_results_pkl(result, fname)
 def test_davis_betweenness_centrality(self):
     G = self.davis
     bet = bipartite.betweenness_centrality(G, self.top_nodes)
     answer = {'E8':0.24,
             'E9':0.23,
             'E7':0.13,
             'Nora Fayette':0.11,
             'Evelyn Jefferson':0.10,
             'Theresa Anderson':0.09,
             'E6':0.07,
             'Sylvia Avondale':0.07,
             'Laura Mandeville':0.05,
             'Brenda Rogers':0.05,
             'Katherina Rogers':0.05,
             'E5':0.04,
             'Helen Lloyd':0.04,
             'E3':0.02,
             'Ruth DeSand':0.02,
             'Verne Sanderson':0.02,
             'E12':0.02,
             'Myra Liddel':0.02,
             'E11':0.02,
             'Eleanor Nye':0.01,
             'Frances Anderson':0.01,
             'Pearl Oglethorpe':0.01,
             'E4':0.01,
             'Charlotte McDowd':0.01,
             'E10':0.01,
             'Olivia Carleton':0.01,
             'Flora Price':0.01,
             'E2':0.00,
             'E1':0.00,
             'Dorothy Murchison':0.00,
             'E13':0.00,
             'E14':0.00}
     for node, value in answer.items():
         assert_almost_equal(value, bet[node], places=2)
    print('#Women, Member')

    for c in clubs:
        print('%d %s' % (W2.degree(c, weight='weight'), c))

    print
    nx.draw(W2, node_color='b', edge_color='r', with_labels=True)
    plt.savefig("davisontoclubsratio.png")  # save as png
    plt.show()  # display
    print
    print
    # Degee Summary Stats
    deg = bipartite.degree_centrality(g, clubs)

    # Betweenness Summary Stats
    bc = bipartite.betweenness_centrality(g, clubs)

    # Closeness Summary Stats
    cc = bipartite.closeness_centrality(g, clubs)

    maxdeg = 0
    mindeg = 9999
    mindegwomen = []
    maxdegwomen = []
    degarray = []

    maxbc = 0
    minbc = 9999
    minbcwomen = []
    maxbcwomen = []
    bcarray = []
Example #9
0
# Centrality Measures
# Do these factor in directedness!!!!!!!!!!!!!!!!!!!!!!!!!???????????????????????
closeness_centrality = bipartite.closeness_centrality(network, users)
total_closeness_centrality = 0
for key, value in closeness_centrality.items():
    total_closeness_centrality += value
avg_closeness_centrality = total_closeness_centrality / len(
    closeness_centrality)

degree_centrality = bipartite.degree_centrality(network, users)
total_degree_centrality = 0
for key, value in degree_centrality.items():
    total_degree_centrality += value
avg_degree_centrality = total_degree_centrality / len(degree_centrality)

betweenness_centrality = bipartite.betweenness_centrality(network, users)
total_betweenness_centrality = 0
for key, value in betweenness_centrality.items():
    total_betweenness_centrality += value
avg_betweenness_centrality = total_betweenness_centrality / len(
    betweenness_centrality)

###################################################
# Projection onto Users considering all edge types#
###################################################
network = nx.DiGraph(network)
user_network = bipartite.projected_graph(network, users, multigraph=True)
print(type(user_network))
exit()

# Degree Measures
Example #10
0
    def describe(self, extra=False):
        """
        Provides a summary of graph statistics. Includes basic statistics like the number of nodes, edges,
        denstiy, and the average degree for one mode. Prints a string that contains each of the items that make up the summary.
        Density is calculated using one of the modes of the original bipartite network graph.

        **Parameters** :

        > *extra* : `bool`

        >> Runs the low efficiency algorithms, which can be resource-intensive on large networks.
        >> Recommended maximum network size for the low efficiency algorithms is around 100 nodes.

        **Returns** : `string`

        > Returns the descriptive string that contains information about the `MultiGraphPlus` object.

        """
        mode1 = self.mode1
        mode2 = self.mode2
        density = bipartite.density(self, bipartite.sets(self)[0])
        edges = self.number_of_edges()
        nodes_mode1 = 0
        nodes_mode2 = 0
        for n in self.nodes():
            if self.node[n]['type'] == mode1:
                nodes_mode1 += 1
            elif self.node[n]['type'] == mode2:
                nodes_mode2 += 1

        descriptives_nodes = "This is a bipartite network of types '{}' and '{}'.\n " \
                             "{} nodes are of the type '{}'.\n " \
                             "{} nodes are of the type '{}'.\n".format(str(mode1), str(mode2), str(nodes_mode1),
                                                                       str(mode1), str(nodes_mode2), str(mode2))
        descriptives_edges = "There are {} edges.\n".format(str(edges))
        descriptives_density = "Density: {}.\n".format(str(density))
        descriptives = descriptives_nodes + descriptives_edges + descriptives_density

        if extra:
            # Note: for each mode of the bipartite graph, degree and betweenness centrality are the same.
            # Keeping them both makes it easy to compare them and make sure they are the same.
            degree_mode1 = bipartite.degree_centrality(self, bipartite.sets(self)[0])
            degree_mode2 = bipartite.degree_centrality(self, bipartite.sets(self)[1])
            degree_mode1 = list(degree_mode1.values())
            degree_mode2 = list(degree_mode2.values())
            degree_mode1 = np.mean(degree_mode1)
            degree_mode2 = np.mean(degree_mode2)
            betweenness_mode1 = bipartite.betweenness_centrality(self, bipartite.sets(self)[0])
            betweenness_mode1 = list(betweenness_mode1.values())
            betweenness_mode1 = np.mean(betweenness_mode1)
            betweenness_mode2 = bipartite.betweenness_centrality(self, bipartite.sets(self)[1])
            betweenness_mode2 = list(betweenness_mode2.values())
            betweenness_mode2 = np.mean(betweenness_mode2)
            g = nx.Graph(self)
            projection = bipartite.projected_graph(g, bipartite.sets(g)[0])
            transitivity = nx.transitivity(projection)
            descriptives_transitivity = "Transitivity: {}.\n".format(str(transitivity))
            descriptives_degree_centrality = "Mean Degree Centrality for '{}': {}.\n" \
                                             "Mean Degree Centrality for '{}': {}.\n".format(str(mode1),
                                                                                             str(degree_mode1),
                                                                                             str(mode2),
                                                                                             str(degree_mode2))
            descriptives_btwn_centrality = "Mean Betweenness Centrality for '{}': {}.\n"\
                                           "Mean Betweenness Centrality for '{}': {}.\n".format(str(mode1),
                                                                                                str(betweenness_mode1),
                                                                                                str(mode2),
                                                                                                str(betweenness_mode2))
            descriptives = descriptives + descriptives_transitivity +\
                descriptives_degree_centrality + descriptives_btwn_centrality
        print(descriptives)
        return descriptives