Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / networkx / algorithms / assortativity / mixing.py @ 5cef0f13

History | View | Annotate | Download (6.69 KB)

1
#-*- coding: utf-8 -*-
2
"""
3
Mixing matrices for node attributes and degree.
4
"""
5
import networkx as nx
6
from networkx.utils import dict_to_numpy_array
7
from networkx.algorithms.assortativity.pairs import node_degree_xy, \
8
    node_attribute_xy
9
__author__ = ' '.join(['Aric Hagberg <aric.hagberg@gmail.com>'])
10
__all__ = ['attribute_mixing_matrix',
11
           'attribute_mixing_dict',
12
           'degree_mixing_matrix',
13
           'degree_mixing_dict',
14
           'numeric_mixing_matrix',
15
           'mixing_dict']
16

    
17

    
18
def attribute_mixing_dict(G, attribute, nodes=None, normalized=False):
19
    """Returns dictionary representation of mixing matrix for attribute.
20

21
    Parameters
22
    ----------
23
    G : graph
24
       NetworkX graph object.
25

26
    attribute : string
27
       Node attribute key.
28

29
    nodes: list or iterable (optional)
30
        Unse nodes in container to build the dict. The default is all nodes.
31

32
    normalized : bool (default=False)
33
       Return counts if False or probabilities if True.
34

35
    Examples
36
    --------
37
    >>> G=nx.Graph()
38
    >>> G.add_nodes_from([0,1],color='red')
39
    >>> G.add_nodes_from([2,3],color='blue')
40
    >>> G.add_edge(1,3)
41
    >>> d=nx.attribute_mixing_dict(G,'color')
42
    >>> print(d['red']['blue'])
43
    1
44
    >>> print(d['blue']['red']) # d symmetric for undirected graphs
45
    1
46

47
    Returns
48
    -------
49
    d : dictionary
50
       Counts or joint probability of occurrence of attribute pairs.
51
    """
52
    xy_iter = node_attribute_xy(G, attribute, nodes)
53
    return mixing_dict(xy_iter, normalized=normalized)
54

    
55

    
56
def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None,
57
                            normalized=True):
58
    """Returns mixing matrix for attribute.
59

60
    Parameters
61
    ----------
62
    G : graph
63
       NetworkX graph object.
64

65
    attribute : string
66
       Node attribute key.
67

68
    nodes: list or iterable (optional)
69
        Use only nodes in container to build the matrix. The default is
70
        all nodes.
71

72
    mapping : dictionary, optional
73
       Mapping from node attribute to integer index in matrix.
74
       If not specified, an arbitrary ordering will be used.
75

76
    normalized : bool (default=True)
77
       Return counts if False or probabilities if True.
78

79
    Returns
80
    -------
81
    m: numpy array
82
       Counts or joint probability of occurrence of attribute pairs.
83
    """
84
    d = attribute_mixing_dict(G, attribute, nodes)
85
    a = dict_to_numpy_array(d, mapping=mapping)
86
    if normalized:
87
        a = a / a.sum()
88
    return a
89

    
90

    
91
def degree_mixing_dict(G, x='out', y='in', weight=None,
92
                       nodes=None, normalized=False):
93
    """Returns dictionary representation of mixing matrix for degree.
94

95
    Parameters
96
    ----------
97
    G : graph
98
        NetworkX graph object.
99

100
    x: string ('in','out')
101
       The degree type for source node (directed graphs only).
102

103
    y: string ('in','out')
104
       The degree type for target node (directed graphs only).
105

106
    weight: string or None, optional (default=None)
107
       The edge attribute that holds the numerical value used
108
       as a weight.  If None, then each edge has weight 1.
109
       The degree is the sum of the edge weights adjacent to the node.
110

111
    normalized : bool (default=False)
112
        Return counts if False or probabilities if True.
113

114
    Returns
115
    -------
116
    d: dictionary
117
       Counts or joint probability of occurrence of degree pairs.
118
    """
119
    xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
120
    return mixing_dict(xy_iter, normalized=normalized)
121

    
122

    
123
def degree_mixing_matrix(G, x='out', y='in', weight=None,
124
                         nodes=None, normalized=True):
125
    """Returns mixing matrix for attribute.
126

127
    Parameters
128
    ----------
129
    G : graph
130
       NetworkX graph object.
131

132
    x: string ('in','out')
133
       The degree type for source node (directed graphs only).
134

135
    y: string ('in','out')
136
       The degree type for target node (directed graphs only).
137

138
    nodes: list or iterable (optional)
139
        Build the matrix using only nodes in container.
140
        The default is all nodes.
141

142
    weight: string or None, optional (default=None)
143
       The edge attribute that holds the numerical value used
144
       as a weight.  If None, then each edge has weight 1.
145
       The degree is the sum of the edge weights adjacent to the node.
146

147
    normalized : bool (default=True)
148
       Return counts if False or probabilities if True.
149

150
    Returns
151
    -------
152
    m: numpy array
153
       Counts, or joint probability, of occurrence of node degree.
154
    """
155
    d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight)
156
    s = set(d.keys())
157
    for k, v in d.items():
158
        s.update(v.keys())
159
    m = max(s)
160
    mapping = {x: x for x in range(m + 1)}
161
    a = dict_to_numpy_array(d, mapping=mapping)
162
    if normalized:
163
        a = a / a.sum()
164
    return a
165

    
166

    
167
def numeric_mixing_matrix(G, attribute, nodes=None, normalized=True):
168
    """Returns numeric mixing matrix for attribute.
169

170
    The attribute must be an integer.
171

172
    Parameters
173
    ----------
174
    G : graph
175
       NetworkX graph object.
176

177
    attribute : string
178
       Node attribute key.  The corresponding attribute must be an integer.
179

180
    nodes: list or iterable (optional)
181
        Build the matrix only with nodes in container. The default is all nodes.
182

183
    normalized : bool (default=True)
184
       Return counts if False or probabilities if True.
185

186
    Returns
187
    -------
188
    m: numpy array
189
       Counts, or joint, probability of occurrence of node attribute pairs.
190
    """
191
    d = attribute_mixing_dict(G, attribute, nodes)
192
    s = set(d.keys())
193
    for k, v in d.items():
194
        s.update(v.keys())
195
    m = max(s)
196
    mapping = {x: x for x in range(m + 1)}
197
    a = dict_to_numpy_array(d, mapping=mapping)
198
    if normalized:
199
        a = a / a.sum()
200
    return a
201

    
202

    
203
def mixing_dict(xy, normalized=False):
204
    """Returns a dictionary representation of mixing matrix.
205

206
    Parameters
207
    ----------
208
    xy : list or container of two-tuples
209
       Pairs of (x,y) items.
210

211
    attribute : string
212
       Node attribute key
213

214
    normalized : bool (default=False)
215
       Return counts if False or probabilities if True.
216

217
    Returns
218
    -------
219
    d: dictionary
220
       Counts or Joint probability of occurrence of values in xy.
221
    """
222
    d = {}
223
    psum = 0.0
224
    for x, y in xy:
225
        if x not in d:
226
            d[x] = {}
227
        if y not in d:
228
            d[y] = {}
229
        v = d[x].get(y, 0)
230
        d[x][y] = v + 1
231
        psum += 1
232

    
233
    if normalized:
234
        for k, jdict in d.items():
235
            for j in jdict:
236
                jdict[j] /= psum
237
    return d
238

    
239

    
240
# fixture for nose tests
241
def setup_module(module):
242
    from nose import SkipTest
243
    try:
244
        import numpy
245
    except:
246
        raise SkipTest("NumPy not available")
247
    try:
248
        import scipy
249
    except:
250
        raise SkipTest("SciPy not available")