2
# Copyright (C) 2011 by
3
# Jordi Torrents <jtorrents@milnou.net>
4
# Aric Hagberg <hagberg@lanl.gov>
7
from collections import defaultdict
9
__author__ = """\n""".join(['Jordi Torrents <jtorrents@milnou.net>',
10
'Aric Hagberg (hagberg@lanl.gov)'])
11
__all__ = ['average_degree_connectivity',
12
'k_nearest_neighbors']
14
def _avg_deg_conn(G, neighbors, source_degree, target_degree,
15
nodes=None, weight=None):
16
# "k nearest neighbors, or neighbor_connectivity
17
dsum = defaultdict(float)
18
dnorm = defaultdict(float)
19
for n,k in source_degree(nodes).items():
20
nbrdeg = target_degree(neighbors(n))
22
s = float(sum(nbrdeg.values()))
23
else: # weight nbr degree by weight of (n,nbr) edge
24
s = float(sum((G[n][nbr].get(weight,1)*d
25
for nbr,d in nbrdeg.items())))
26
dnorm[k] += source_degree(n, weight=weight)
31
for k,avg in dsum.items():
34
if avg > 0 and norm > 0:
38
def average_degree_connectivity(G, source="in+out", target="in+out",
39
nodes=None, weight=None):
40
r"""Compute the average degree connectivity of graph.
42
The average degree connectivity is the average nearest neighbor degree of
43
nodes with degree k. For weighted graphs, an analogous measure can
44
be computed using the weighted average neighbors degree defined in
45
[1]_, for a node `i`, as:
49
k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
51
where `s_i` is the weighted degree of node `i`,
52
`w_{ij}` is the weight of the edge that links `i` and `j`,
53
and `N(i)` are the neighbors of node `i`.
59
source : "in"|"out"|"in+out" (default:"in+out")
60
Directed graphs only. Use "in"- or "out"-degree for source node.
62
target : "in"|"out"|"in+out" (default:"in+out"
63
Directed graphs only. Use "in"- or "out"-degree for target node.
65
nodes: list or iterable (optional)
66
Compute neighbor connectivity for these nodes. The default is all nodes.
68
weight : string or None, optional (default=None)
69
The edge attribute that holds the numerical value used as a weight.
70
If None, then each edge has weight 1.
75
A dictionary keyed by degree k with the value of average connectivity.
79
>>> G=nx.path_graph(4)
80
>>> G.edge[1][2]['weight'] = 3
81
>>> nx.k_nearest_neighbors(G)
83
>>> nx.k_nearest_neighbors(G, weight='weight')
88
neighbors_average_degree
92
This algorithm is sometimes called "k nearest neighbors'.
96
.. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
97
"The architecture of complex weighted networks".
98
PNAS 101 (11): 3747–3752 (2004).
100
source_degree = G.degree
101
target_degree = G.degree
102
neighbors = G.neighbors
104
direction = {'out':G.out_degree,
107
source_degree = direction[source]
108
target_degree = direction[target]
110
neighbors=G.predecessors
111
elif source == 'out':
112
neighbors=G.successors
113
return _avg_deg_conn(G, neighbors, source_degree, target_degree,
114
nodes=nodes, weight=weight)
116
k_nearest_neighbors=average_degree_connectivity