__init__.py 9.19 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
#! /usr/bin/env python
2
# -*- coding: utf-8 -*-
Tiago Peixoto's avatar
Tiago Peixoto committed
3
#
4
5
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2013 Tiago de Paula Peixoto <tiago@skewed.de>
Tiago Peixoto's avatar
Tiago Peixoto committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
``graph_tool.spectral`` - Spectral properties
---------------------------------------------
24
25
26
27
28
29
30
31
32
33
34
35
36

Summary
+++++++

.. autosummary::
   :nosignatures:

   adjacency
   laplacian
   incidence

Contents
++++++++
Tiago Peixoto's avatar
Tiago Peixoto committed
37
38
"""

39
40
from __future__ import division, absolute_import, print_function

41
from .. import _degree, _prop, Graph, _limit_args
Tiago Peixoto's avatar
Tiago Peixoto committed
42
43
44
45
46
47
from numpy import *
import scipy.sparse


__all__ = ["adjacency", "laplacian", "incidence"]

48

Tiago Peixoto's avatar
Tiago Peixoto committed
49
def adjacency(g, sparse=True, weight=None):
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    r"""Return the adjacency matrix of the graph.

    Parameters
    ----------
    g : Graph
        Graph to be used.
    sparse : bool (optional, default: True)
        Build a :mod:`~scipy.sparse` matrix.
    weight : PropertyMap (optional, default: True)
        Edge property map with the edge weights.

    Returns
    -------
    a : matrix
        The adjacency matrix.

    Notes
    -----
    The adjacency matrix is defined as

    .. math::

        a_{i,j} =
        \begin{cases}
            1 & \text{if } v_i \text{ is adjacent to } v_j, \\
            0 & \text{otherwise}
        \end{cases}

    In the case of weighted edges, the value 1 is replaced the weight of the
    respective edge.

81
82
83
    In the case of networks with parallel edges, the entries in the matrix
    become simply the edge multiplicities.

84
85
    Examples
    --------
86
87
88
89
90
    .. testsetup::

      gt.seed_rng(42)

    >>> g = gt.random_graph(100, lambda: (10, 10))
91
    >>> m = gt.adjacency(g)
92
    >>> print(m.todense())
Tiago Peixoto's avatar
Tiago Peixoto committed
93
    [[ 0.  0.  0. ...,  0.  1.  0.]
94
     [ 0.  0.  0. ...,  0.  0.  0.]
Tiago Peixoto's avatar
Tiago Peixoto committed
95
     [ 0.  0.  0. ...,  0.  0.  1.]
Tiago Peixoto's avatar
Tiago Peixoto committed
96
     ..., 
97
     [ 0.  0.  0. ...,  0.  0.  0.]
Tiago Peixoto's avatar
Tiago Peixoto committed
98
99
     [ 0.  0.  0. ...,  0.  0.  0.]
     [ 0.  0.  1. ...,  0.  0.  0.]]
100
101
102

    References
    ----------
103
    .. [wikipedia-adjacency] http://en.wikipedia.org/wiki/Adjacency_matrix
104
105
    """

Tiago Peixoto's avatar
Tiago Peixoto committed
106
107
    if g.get_vertex_filter()[0] != None:
        index = g.new_vertex_property("int64_t")
Tiago Peixoto's avatar
Tiago Peixoto committed
108
        for i, v in enumerate(g.vertices()):
Tiago Peixoto's avatar
Tiago Peixoto committed
109
110
111
112
113
            index[v] = i
    else:
        index = g.vertex_index
    N = g.num_vertices()
    if sparse:
Tiago Peixoto's avatar
Tiago Peixoto committed
114
        m = scipy.sparse.lil_matrix((N, N))
Tiago Peixoto's avatar
Tiago Peixoto committed
115
    else:
Tiago Peixoto's avatar
Tiago Peixoto committed
116
        m = matrix(zeros((N, N)))
Tiago Peixoto's avatar
Tiago Peixoto committed
117
118
    for v in g.vertices():
        for e in v.out_edges():
119
            m[index[v], index[e.target()]] += 1 if weight is None else weight[e]
Tiago Peixoto's avatar
Tiago Peixoto committed
120
121
122
123
    if sparse:
        m = m.tocsr()
    return m

Tiago Peixoto's avatar
Tiago Peixoto committed
124

Tiago Peixoto's avatar
Tiago Peixoto committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def _get_deg(v, deg, weight):
    if deg == "total":
        if weight == None:
            d = v.in_degree() + v.out_degree()
        else:
            d = sum(weight[e] for e in v.all_edges())
    elif deg == "in":
        if weight == None:
            d = v.in_degree()
        else:
            d = sum(weight[e] for e in v.in_edges())
    else:
        if weight == None:
            d = v.out_degree()
        else:
            d = sum(weight[e] for e in v.out_edges())
    return d

Tiago Peixoto's avatar
Tiago Peixoto committed
143
144

@_limit_args({"deg": ["total", "in", "out"]})
Tiago Peixoto's avatar
Tiago Peixoto committed
145
def laplacian(g, deg="total", normalized=True, sparse=True, weight=None):
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    r"""Return the Laplacian matrix of the graph.

    Parameters
    ----------
    g : Graph
        Graph to be used.
    deg : str (optional, default: "total")
        Degree to be used, in case of a directed graph.
    normalized : bool (optional, default: True)
        Whether to compute the normalized Laplacian.
    sparse : bool (optional, default: True)
        Build a :mod:`~scipy.sparse` matrix.
    weight : PropertyMap (optional, default: True)
        Edge property map with the edge weights.

    Returns
    -------
    l : matrix
        The Laplacian matrix.

    Notes
    -----
Tiago Peixoto's avatar
Tiago Peixoto committed
168
    The weighted Laplacian matrix is defined as
169
170
171

    .. math::

Tiago Peixoto's avatar
Tiago Peixoto committed
172
        \ell_{ij} =
173
174
        \begin{cases}
        \Gamma(v_i) & \text{if } i = j \\
Tiago Peixoto's avatar
Tiago Peixoto committed
175
        -w_{ij}     & \text{if } i \neq j \text{ and } v_i \text{ is adjacent to } v_j \\
176
177
178
        0           & \text{otherwise}.
        \end{cases}

Tiago Peixoto's avatar
Tiago Peixoto committed
179
180
    Where :math:`\Gamma(v_i)=\sum_j A_{ij}w_{ij}` is sum of the weights of
    vertex :math:`v_i`. The normalized version is
181
182
183

    .. math::

Tiago Peixoto's avatar
Tiago Peixoto committed
184
        \ell_{ij} =
185
186
        \begin{cases}
        1         & \text{ if } i = j \text{ and } \Gamma(v_i) \neq 0 \\
Tiago Peixoto's avatar
Tiago Peixoto committed
187
        -\frac{w_{ij}}{\sqrt{\Gamma(v_i)\Gamma(v_j)}} & \text{ if } i \neq j \text{ and } v_i \text{ is adjacent to } v_j \\
188
189
190
        0         & \text{otherwise}.
        \end{cases}

Tiago Peixoto's avatar
Tiago Peixoto committed
191
192
193
194
195
    In the case of unweighted edges, it is assumed :math:`w_{ij} = 1`.

    For directed graphs, it is assumed :math:`\Gamma(v_i)=\sum_j A_{ij}w_{ij} +
    \sum_j A_{ji}w_{ji}` if ``deg=="total"``, :math:`\Gamma(v_i)=\sum_j A_{ij}w_{ij}`
    if ``deg=="out"`` or :math:`\Gamma(v_i)=\sum_j A_{ji}w_{ji}` ``deg=="in"``.
196
197
198

    Examples
    --------
199
200
201
202
    .. testsetup::

      gt.seed_rng(42)

203
204
    >>> g = gt.random_graph(100, lambda: (10,10))
    >>> m = gt.laplacian(g)
205
    >>> print(m.todense())
Tiago Peixoto's avatar
Tiago Peixoto committed
206
207
208
    [[ 1.   -0.05  0.   ...,  0.    0.    0.  ]
     [ 0.    1.    0.   ...,  0.    0.   -0.05]
     [ 0.    0.    1.   ...,  0.   -0.05  0.  ]
Tiago Peixoto's avatar
Tiago Peixoto committed
209
     ..., 
Tiago Peixoto's avatar
Tiago Peixoto committed
210
211
212
     [ 0.    0.    0.   ...,  1.    0.    0.  ]
     [-0.05  0.    0.   ...,  0.    1.    0.  ]
     [ 0.    0.    0.   ..., -0.05  0.    1.  ]]
213
214
215

    References
    ----------
216
    .. [wikipedia-laplacian] http://en.wikipedia.org/wiki/Laplacian_matrix
217
218
    """

Tiago Peixoto's avatar
Tiago Peixoto committed
219
220
    if g.get_vertex_filter()[0] != None:
        index = g.new_vertex_property("int64_t")
Tiago Peixoto's avatar
Tiago Peixoto committed
221
        for i, v in enumerate(g.vertices()):
Tiago Peixoto's avatar
Tiago Peixoto committed
222
223
224
225
226
            index[v] = i
    else:
        index = g.vertex_index
    N = g.num_vertices()
    if sparse:
Tiago Peixoto's avatar
Tiago Peixoto committed
227
        m = scipy.sparse.lil_matrix((N, N))
Tiago Peixoto's avatar
Tiago Peixoto committed
228
    else:
Tiago Peixoto's avatar
Tiago Peixoto committed
229
        m = matrix(zeros((N, N)))
Tiago Peixoto's avatar
Tiago Peixoto committed
230
231
232
233
    for v in g.vertices():
        d = _get_deg(v, deg, weight)
        for e in v.out_edges():
            if not normalized:
234
235
236
237
238
239
                if weight is None:
                    val = -1
                else:
                    val = -weight[e]
                # increment in case of parallel edges
                m[index[v], index[e.target()]] += val
Tiago Peixoto's avatar
Tiago Peixoto committed
240
            else:
241
242
243
244
245
246
247
                d2 = _get_deg(e.target(), deg, weight)
                if weight is None:
                    w = 1
                else:
                    w = weight[e]
                # increment in case of parallel edges
                m[index[v], index[e.target()]] += - w / sqrt(d * d2)
248
249
250
        if not normalized:
            m[index[v], index[v]] = d
        elif d > 0:
251
            m[index[v], index[v]] = 1 if d != 0 else 0
Tiago Peixoto's avatar
Tiago Peixoto committed
252
253
254
255
    if sparse:
        m = m.tocsr()
    return m

Tiago Peixoto's avatar
Tiago Peixoto committed
256

Tiago Peixoto's avatar
Tiago Peixoto committed
257
def incidence(g, sparse=True):
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
    r"""Return the incidence matrix of the graph.

    Parameters
    ----------
    g : Graph
        Graph to be used.
    sparse : bool (optional, default: True)
        Build a :mod:`~scipy.sparse` matrix.

    Returns
    -------
    a : matrix
        The adjacency matrix.

    Notes
    -----
    For undirected graphs, the incidence matrix is defined as

    .. math::

        b_{i,j} =
        \begin{cases}
            1 & \text{if vertex } v_i \text{and edge } e_j \text{ are incident}, \\
            0 & \text{otherwise}
        \end{cases}

    For directed graphs, the definition is

    .. math::

        b_{i,j} =
        \begin{cases}
            1 & \text{if edge } e_j \text{ enters vertex } v_i, \\
            -1 & \text{if edge } e_j \text{ leaves vertex } v_i, \\
            0 & \text{otherwise}
        \end{cases}

    Examples
    --------
297
298
299
300
    .. testsetup::

      gt.seed_rng(42)

301
302
    >>> g = gt.random_graph(100, lambda: (2,2))
    >>> m = gt.incidence(g)
303
    >>> print(m.todense())
Tiago Peixoto's avatar
Tiago Peixoto committed
304
305
    [[-1. -1.  0. ...,  0.  0.  0.]
     [ 0.  0. -1. ...,  0.  0.  0.]
306
     [ 0.  0.  0. ...,  0.  0.  0.]
Tiago Peixoto's avatar
Tiago Peixoto committed
307
     ..., 
308
     [ 0.  0.  0. ...,  0.  0.  0.]
Tiago Peixoto's avatar
Tiago Peixoto committed
309
310
     [ 0.  0.  0. ..., -1.  0.  0.]
     [ 0.  0.  0. ...,  0. -1. -1.]]
311
312
313

    References
    ----------
314
    .. [wikipedia-incidence] http://en.wikipedia.org/wiki/Incidence_matrix
315
316
    """

Tiago Peixoto's avatar
Tiago Peixoto committed
317
318
    if g.get_vertex_filter()[0] != None:
        index = g.new_vertex_property("int64_t")
Tiago Peixoto's avatar
Tiago Peixoto committed
319
        for i, v in enumerate(g.vertices()):
Tiago Peixoto's avatar
Tiago Peixoto committed
320
321
322
323
324
325
326
327
328
329
330
            index[v] = i
    else:
        index = g.vertex_index

    eindex = g.new_edge_property("int64_t")
    for i, e in enumerate(g.edges()):
        eindex[e] = i

    N = g.num_vertices()
    E = g.num_edges()
    if sparse:
Tiago Peixoto's avatar
Tiago Peixoto committed
331
        m = scipy.sparse.lil_matrix((N, E))
Tiago Peixoto's avatar
Tiago Peixoto committed
332
    else:
Tiago Peixoto's avatar
Tiago Peixoto committed
333
        m = matrix(zeros((N, E)))
Tiago Peixoto's avatar
Tiago Peixoto committed
334
335
336
    for v in g.vertices():
        if g.is_directed():
            for e in v.out_edges():
Tiago Peixoto's avatar
Tiago Peixoto committed
337
                m[index[v], eindex[e]] += -1
Tiago Peixoto's avatar
Tiago Peixoto committed
338
            for e in v.in_edges():
Tiago Peixoto's avatar
Tiago Peixoto committed
339
                m[index[v], eindex[e]] += 1
Tiago Peixoto's avatar
Tiago Peixoto committed
340
341
        else:
            for e in v.out_edges():
Tiago Peixoto's avatar
Tiago Peixoto committed
342
                m[index[v], eindex[e]] += 1
Tiago Peixoto's avatar
Tiago Peixoto committed
343
344
345
    if sparse:
        m = m.tocsr()
    return m