Python networkx.eigenvector_centrality() Examples

The following are 23 code examples of networkx.eigenvector_centrality(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: analyse_meg_epilepsy_clips.py    From mmvt with GNU General Public License v3.0 8 votes vote down vote up
def _calc_graph_func(p):
    con, times_chunk, graph_func = p
    vals = []
    now = time.time()
    for run, t in enumerate(times_chunk):
        utils.time_to_go(now, run, len(times_chunk), 10)
        con_t = con[:, :, t]
        g = nx.from_numpy_matrix(con_t)
        if graph_func == 'closeness_centrality':
            x = nx.closeness_centrality(g)
        elif graph_func == 'degree_centrality':
            x = nx.degree_centrality(g)
        elif graph_func == 'eigenvector_centrality':
            x = nx.eigenvector_centrality(g, max_iter=10000)
        elif graph_func == 'katz_centrality':
            x = nx.katz_centrality(g, max_iter=100000)
        else:
            raise Exception('Wrong graph func!')
        vals.append([x[k] for k in range(len(x))])
    vals = np.array(vals)
    return vals, times_chunk 
Example #2
Source File: test_eigenvector_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 7 votes vote down vote up
def test_K5(self):
        """Eigenvector centrality: K5"""
        G=networkx.complete_graph(5)
        b=networkx.eigenvector_centrality(G)
        v=math.sqrt(1/5.0)
        b_answer=dict.fromkeys(G,v)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n])
        nstart = dict([(n,1) for n in G])
        b=networkx.eigenvector_centrality(G,nstart=nstart)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n])


        b=networkx.eigenvector_centrality_numpy(G)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n],places=3) 
Example #3
Source File: test_eigenvector_centrality.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_K5(self):
        """Eigenvector centrality: K5"""
        G=nx.complete_graph(5)
        b=nx.eigenvector_centrality(G)
        v=math.sqrt(1/5.0)
        b_answer=dict.fromkeys(G,v)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n])
        nstart = dict([(n,1) for n in G])
        b=nx.eigenvector_centrality(G,nstart=nstart)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n])


        b=nx.eigenvector_centrality_numpy(G)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n],places=3) 
Example #4
Source File: test_eigenvector_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_K5(self):
        """Eigenvector centrality: K5"""
        G = nx.complete_graph(5)
        b = nx.eigenvector_centrality(G)
        v = math.sqrt(1 / 5.0)
        b_answer = dict.fromkeys(G, v)
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n])
        nstart = dict([(n, 1) for n in G])
        b = nx.eigenvector_centrality(G, nstart=nstart)
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n])

        b = nx.eigenvector_centrality_numpy(G)
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n], places=3) 
Example #5
Source File: test_eigenvector_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_empty(self):
        e = nx.eigenvector_centrality(nx.Graph()) 
Example #6
Source File: infectious_disease_agents_test.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def test_interact_with_env_replicable_randomagent(self):
    graph = nx.karate_club_graph()
    centrality = nx.eigenvector_centrality(graph)
    sorted_nodes = sorted(
        centrality.keys(), key=lambda k: centrality[k], reverse=True)
    # Infect the 3rd through 5th most central people.
    initial_health_state = [
        1 if index in sorted_nodes[3:6] else 0
        for index in range(len(sorted_nodes))
    ]
    env, agent, _ = set_up_and_observe(
        population_graph=graph,
        initial_health_state=initial_health_state,
        agent_class=infectious_disease_agents.RandomAgent)
    test_util.run_test_simulation(env=env, agent=agent) 
Example #7
Source File: test_eigenvector_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_eigenvector_centrality_unweighted(self):
        G=self.H
        p=nx.eigenvector_centrality(G)
        for (a,b) in zip(list(p.values()),self.G.evc):
            assert_almost_equal(a,b,places=4) 
Example #8
Source File: test_eigenvector_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_eigenvector_centrality_weighted(self):
        G=self.G
        p=nx.eigenvector_centrality(G)
        for (a,b) in zip(list(p.values()),self.G.evc):
            assert_almost_equal(a,b,places=4) 
Example #9
Source File: test_eigenvector_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_maxiter(self):
        G=nx.path_graph(3)
        b=nx.eigenvector_centrality(G,max_iter=0) 
Example #10
Source File: test_eigenvector_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_P3(self):
        """Eigenvector centrality: P3"""
        G=nx.path_graph(3)
        b_answer={0: 0.5, 1: 0.7071, 2: 0.5}
        b=nx.eigenvector_centrality_numpy(G)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n],places=4)
        b=nx.eigenvector_centrality(G)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n],places=4) 
Example #11
Source File: test_eigenvector_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty(self):
        e = nx.eigenvector_centrality(nx.Graph()) 
Example #12
Source File: test_eigenvector_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_eigenvector_centrality_unweighted(self):
        G = self.H
        p = nx.eigenvector_centrality(G)
        for (a, b) in zip(list(p.values()), self.G.evc):
            assert_almost_equal(a, b, places=4) 
Example #13
Source File: test_eigenvector_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_eigenvector_centrality_weighted(self):
        G = self.G
        p = nx.eigenvector_centrality(G)
        for (a, b) in zip(list(p.values()), self.G.evc):
            assert_almost_equal(a, b, places=4) 
Example #14
Source File: test_eigenvector_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_maxiter(self):
        G = nx.path_graph(3)
        b = nx.eigenvector_centrality(G, max_iter=0) 
Example #15
Source File: test_eigenvector_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_P3(self):
        """Eigenvector centrality: P3"""
        G = nx.path_graph(3)
        b_answer = {0: 0.5, 1: 0.7071, 2: 0.5}
        b = nx.eigenvector_centrality_numpy(G)
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n], places=4)
        b = nx.eigenvector_centrality(G)
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n], places=4) 
Example #16
Source File: test_eigenvector_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_multigraph(self):
        e = networkx.eigenvector_centrality(networkx.MultiGraph()) 
Example #17
Source File: test_eigenvector_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_eigenvector_centrality_unweighted(self):
        G=self.H
        p=networkx.eigenvector_centrality(G)
        for (a,b) in zip(list(p.values()),self.G.evc):
            assert_almost_equal(a,b,places=4) 
Example #18
Source File: test_eigenvector_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_eigenvector_centrality_weighted(self):
        G=self.G
        p=networkx.eigenvector_centrality(G)
        for (a,b) in zip(list(p.values()),self.G.evc):
            assert_almost_equal(a,b,places=4) 
Example #19
Source File: test_eigenvector_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_maxiter(self):
        G=networkx.path_graph(3)
        b=networkx.eigenvector_centrality(G,max_iter=0) 
Example #20
Source File: infectious_disease_agents.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def _triage(self, observation):
    """Returns person indices ordered from first to last person to treat.

    Infected people are prioritized above non-infected people, and infected
    people are ranked according to their centrality in the contact graph.

    Args:
      observation: An observation from a Dict Space with 'health_states' and
        'population_graph' keys.  The 'health_states' observation contains the
        health states of the population, and the 'population_graph' observation
        contains the contact graph over which disease spreads.

    Returns:
      A numpy array of population indices representing the triage order.
    """
    infections = _infection_indicator(
        observation['health_states'], self.initial_params.infectious_index)
    centrality = nx.eigenvector_centrality(observation['population_graph'])

    # Negate because lower scores are treated first. Note that centrality is a
    # dict that maps from node-keys to centrality values, and it happens
    # that the node keys are zero-counted contiguouos integers, which is
    # required for the following enumeration-based indexing to work out.  This
    # condition is checked by the assertion immediately below.
    assert list(
        observation['population_graph'].nodes()) == list(
            range(observation['population_graph'].number_of_nodes()))
    triage_scores = np.array([
        -infection * centrality[i] for i, infection in enumerate(infections)])

    max_treatments = len(self.action_space.nvec)
    return np.argsort(triage_scores)[:max_treatments] 
Example #21
Source File: infectious_disease_agents_test.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def test_centrality_treatment_ordering_correct(self):
    # Initialize a small example graph and sort nodes by their centrality.
    graph = nx.karate_club_graph()
    centrality = nx.eigenvector_centrality(graph)
    sorted_nodes = sorted(
        centrality.keys(),
        key=lambda k: centrality[k],
        reverse=True)

    # Infect the 3rd through 5th most central people.  We expect these people to
    # be the 1st through 3rd people to receive treatment.
    initial_health_state = [
        1 if index in sorted_nodes[3:6] else 0
        for index in range(len(sorted_nodes))]

    # Initialize an environment with that initial health state and a centrality
    # agent.
    env, agent = instantiate_environment_and_agent(
        agent_class=infectious_disease_agents.CentralityAgent,
        population_graph=graph,
        initial_health_state=initial_health_state)

    # Confirm that the infected people are sorted by centrality in the agent's
    # action.  We expect 3rd the through 5th most central people to be the 1st
    # through 3rd people to receive treatment.
    observation = env._get_observable_state()
    action = agent.act(observation, False)
    self.assertEqual(sorted_nodes[3:6], action[:3].tolist()) 
Example #22
Source File: infectious_disease_agents_test.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def test_interact_with_env_replicable_centralityagent(self):
    graph = nx.karate_club_graph()
    centrality = nx.eigenvector_centrality(graph)
    sorted_nodes = sorted(
        centrality.keys(), key=lambda k: centrality[k], reverse=True)
    # Infect the 3rd through 5th most central people.
    initial_health_state = [
        1 if index in sorted_nodes[3:6] else 0
        for index in range(len(sorted_nodes))
    ]
    env, agent, _ = set_up_and_observe(
        population_graph=graph,
        initial_health_state=initial_health_state,
        agent_class=infectious_disease_agents.CentralityAgent)
    test_util.run_test_simulation(env=env, agent=agent) 
Example #23
Source File: PercoMCV.py    From cdlib with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def percoMVC(g):
    # Zachary's Karate club example
    c = list(__k_clique_communities(g))

    m2 = set()
    coms = []
    for com in c:
        coms_list = list(com)
        coms += [coms_list]
        m1 = set(coms_list)
        m2 = m2 | m1

    t = []
    p = 1
    while p <= len(g.nodes):
        t.append(p)
        p += 1
    t = set(t)
    nodn_classes = t - m2

    # Second step
    # Trying to classify unclassified nodes7

    nodn_classes = sorted(nodn_classes)

    for Com in range(len(coms)):
        if len(coms[Com]) > 3:  # Check si la communauté à plus de 3 noeud

            sub = g.subgraph(coms[Com])

            # Calcul de la centralité de vecteur propre
            centrality = nx.eigenvector_centrality(sub)
            vercteur_pr = sorted((round((centrality[node]), 2), node) for node in centrality)
            for vect in range(len(vercteur_pr)):
                centralitiness = vercteur_pr[vect][0] / vercteur_pr[len(vercteur_pr) - 1][0]
                if centralitiness >= 0.99:  # check if the node is 99% central
                    neud_central = vercteur_pr[vect][1]
                    for nod in range(len(nodn_classes)):
                        if g.has_edge(nodn_classes[nod], neud_central):
                            coms[Com] += [nodn_classes[nod]]

    return coms