graph_tool.py 42.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#! /usr/bin/env python
# graph_tool.py -- a general graph manipulation python module
#
# Copyright (C) 2007 Tiago de Paula Peixoto <tiago@forked.de>
#
# 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/>.

__author__="Tiago de Paula Peixoto <tiago@forked.de>"
__copyright__="Copyright 2007 Tiago de Paula Peixoto"
__license__="GPL version 3 or above"
__URL__="http://graph-tool.forked.de"

__all__ = ["Graph", "GraphError"]

import libgraph_tool
__version__ = libgraph_tool.mod_info().version

import sys, os, os.path, re, struct, fcntl, termios, gzip, bz2, string,\
       textwrap, time, signal, traceback, shutil, time, math, inspect, \
       functools, types

################################################################################
# Utility functions
################################################################################

def _open_file(name, mode="w"):
    """Open the file correctly, according to its file name"""
    if name == "-":
        if mode == "r":
            return sys.stdin
        else:
            return sys.stdout
    name = os.path.expanduser(name)
    if name.endswith("bz2"):
        return bz2.BZ2File(name, mode)
    if name.endswith("gz"):
        return gzip.GzipFile(name, mode)
    return file(name, mode)

def _eval_expr(expr, vars=dict(), edit_expr=False):
    """Evaluats a given python expression into a callable function, which
    returns the evaluation of the last statement. If exp is not a string, return
    it intact."""

    if expr.__class__ != str:
        return expr
    else:
        import random
        vars.update(dict([(x, eval("random."+x)) for x in dir(random) \
                          if not x.startswith("_")]))
        import math
        vars.update(dict([(x, eval("math."+x)) for x in dir(math) \
                          if not x.startswith("_")]))

        # Load some specific functions form scipy if available (and only on
        # demand)
        try:
            if 'gamaincc' in expr:
                from scipy.special import gammaincc
                vars['gamaincc'] = gammaincc
            if 'fsolve' in expr:
                from scipy.optimize import fsolve
                vars['fsolve'] = fsolve
        except ImportError:
            pass

        vars['inv_poisson'] = inv_poisson
        vars['inv_exponential'] = inv_exponential
        vars['inv_power_law'] = inv_power_law

        # Evaluate all statements
        r = re.compile(r"((('[^']*')|(\"[^\"']*\"))|([^;]+)(?=;|$))")
        statements = [x[0].strip() for x in r.findall(expr)]
        file_re = re.compile(r"^import:(.*)")
        for s in statements[:-1]:
            m = file_re.match(s)
            if m != None:
                # Import code from file
                file_name = m.group(1)
                exec _open_file(file_name.strip(), mode="r") in vars
            else:
                exec s in vars

        # Last statement must be returned as a function
        last = statements[-1].strip()
        if last.startswith("lambda ") or last.startswith("lambda:") or \
               last in vars:
            return eval(last, vars)
        else:
            if edit_expr == False:
                return eval("lambda: " + last, vars)
            else:
                if edit_expr != "g":
                    return eval("lambda %s, g: " % edit_expr + last, vars)
                else:
                    return eval("lambda g: " + last, vars)

def _get_mean(hist):
    """Get the mean, and the standard deviation fo the mean, for a given
    histogram."""
    avg, dev, count = 0.0, 0.0, 0.0
    try:
        for k, v in hist.iteritems():
            avg += k*v
            count += v
        avg /= count
        for k, v in hist.iteritems():
            dev += (k - avg)**2
        dev = math.sqrt(dev/(count**2))
    except ZeroDivisionError:
        avg = dev = float("nan") # nans are ok, since graph can be empty
    return (avg, dev)

def _degree(name):
    """Retrieve the degree type from string"""
    deg = name
    if name == "in-degree" or name == "in":
        deg = libgraph_tool.Degree.In
    if name == "out-degree" or name == "out":
        deg = libgraph_tool.Degree.Out
    if name == "total-degree" or name == "total":
        deg = libgraph_tool.Degree.Total
    return deg

def _parse_range(range):
    """Parse a range in the form 'lower[*] upper[*]' (where an '*' indicates
    a closed boundary) or 'comp val', where 'comp' is [==|=|!=|>=|<=|>|<].
    """
    try:
        rcomp = re.compile(r"(>|<|>=|<=|==|=|!=)\s*([^=<>!]+)")
        rrange = re.compile(r"([^\*]+)(\*?)\s+([^\*]+)(\*?)")
        inverted = False
        if rcomp.match(range):
            comp = rcomp.match(range).group(1)
            thres = rcomp.match(range).group(2)
            thres = float(thres)
            if "<" in comp:
                ran = (float('-Inf'), thres)
                if "=" in comp:
                    inc = (False, True)
                else:
                    inc = (False, False)
            elif ">" in comp:
                ran = (thres, float('Inf'))
                if "=" in comp:
                    inc = (True, False)
                else:
                    inc = (False, False)
            elif comp == "==" or comp == "=" or comp == "!=":
                ran = (thres, thres)
                inc = (True, True)
                if comp == "!=":
                    inverted = True
        elif rrange.match(range):
            m = rrange.match(range)
            r1 = float(m.group(1))
            i1 = "*" in m.group(2)
            r2 = float(m.group(3))
            i2 = "*" in m.group(4)
            ran = (r1, r2)
            inc = (i1, i2)
        else:
            raise ValueError("invalid value for range: " + range)
    except (ValueError, TypeError), e:
        raise ValueError("invalid value for range: %s: %s " % (range, str(e)))
    return (ran, inc, inverted)

# Some other predefined functions
# TODO: put them in a more convenient place... an util submodule, perhaps?
def inv_poisson(p, m):
    """returns the inverse of the poisson distribution, with average m"""
    from scipy.optimize import fsolve
    from scipy.special import gammaincc
    return int(round(fsolve(lambda k, l: gammaincc(k, l)-p, m, (m))-0.5+1e-15))
    # FIXME: the 1e-15 constant hack is ugly

def inv_exponential(p, m):
    """returns the inverse of the discrete exponential distibution, with average
    m"""
    return int(round(log(1-p)/log(float(m)/(m+1))-0.5+1e-15))
    # FIXME: the 1e-15 constant hack is ugly

def inv_power_law(p, b):
    """returns the inverse of the discrete power-law distibution, with exponent
    b"""
    return int(round((1-p)**(-1/(b-1)) - 1))

################################################################################
# Decorators
# Some useful function decorators which will be used below
################################################################################

def _wraps(func):
    """This decorator works like the functools.wraps meta-decorator, but
    also preserves the function's argument signature. This uses eval, and is
    thus a bit of a hack, but there no better way I know of to do this."""
    def decorate(f):
        argspec = inspect.getargspec(func)
        args_call = inspect.formatargspec(argspec[0])
        argspec = inspect.formatargspec(argspec[0], defaults=argspec[3])
        argspec = argspec.lstrip("(").rstrip(")")
        wrap = eval("lambda %s: f%s" % (argspec, args_call), locals())
        return functools.wraps(func)(wrap)
    return decorate

def _attrs(**kwds):
    """Decorator which adds arbitrary attributes to methods"""
    def decorate(f):
        for k in kwds:
            setattr(f, k, kwds[k])
        return f
    return decorate

def _handle_exceptions(func):
    """Decorator which will catch and properly propagate exceptions raised
    by GraphInterface in all the methods"""
    @_wraps(func)
    def wrap(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except (IOError, RuntimeError), e:
            raise GraphError(args[0], str(e))
    return wrap

def _limit_args(allowed_vals):
    """Decorator which will limit the values of given arguments to a specified
    list of allowed values, and raise TypeError exception if the given value
    doesn't belong. 'allowed_vals' is a dict containing the allowed value list
    for each limited function argument."""
    def decorate(func):
        @_wraps(func)
        def wrap(*args, **kwargs):
            arg_names = inspect.getargspec(func)[0]
            arguments = zip(arg_names, args)
            arguments += [(k, kwargs[k]) for k in kwargs.keys()]
            for a in arguments:
                if allowed_vals.has_key(a[0]):
                    if a[1] not in allowed_vals[a[0]]:
                        raise TypeError("value for '%s' must be one of: %s" % \
                                         (a[0], ", ".join(allowed_vals[a[0]])))
            return func(*args, **kwargs)
        return wrap
    return decorate

256
257
258
259
260
261
262
263
264
265
266
267
268
def _lazy_load(func):
    """Decorator which will call the 'load' method before executing the
    decorated function, thus implementing 'lazy loading'."""
    @_wraps(func)
    def wrap(*args, **kwargs):
        self = args[0]
        if self.lazy_filename != None and self.lazy_format != None:
            self.load(self.lazy_filename, self.lazy_format)
            self.lazy_filename = None
            self.lazy_format = None
        return func(*args, **kwargs)
    return wrap

269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
################################################################################
# Graph class
# The main graph interface
################################################################################

class GraphError(Exception):
    """Exception raised by the Graph class"""
    def __init__(self, graph, message):
        self.graph = graph
        self.message = message
    def __str__(self):
        return self.message

class Graph(object):
    """The main graph type which encapsulates the GraphInterface"""

    def __init__(self):
        self.__graph = libgraph_tool.GraphInterface()
287
288
        self.lazy_filename = None
        self.lazy_format = None
289
290
291
292

    # Graph access

    @_handle_exceptions
293
    @_lazy_load
294
295
296
297
298
    def vertices(self):
        "Return iterator over the vertices"
        return self.__graph.Vertices()

    @_handle_exceptions
299
    @_lazy_load
300
301
302
303
304
    def edges(self):
        "Return iterator over the edges"
        return self.__graph.Edges()

    @_handle_exceptions
305
    @_lazy_load
306
307
308
309
310
    def add_vertex(self):
        "Add a new vertex to the graph, and return it"
        return self.__graph.AddVertex()

    @_handle_exceptions
311
    @_lazy_load
312
313
314
315
316
    def remove_vertex(self, vertex):
        "Remove a vertex from the graph"
        return self.__graph.RemoveVertex(vertex)

    @_handle_exceptions
317
    @_lazy_load
318
319
320
321
322
    def add_edge(self, source, target):
        "Add a new edge from 'source' to 'target' to the graph, and return it"
        return self.__graph.AddEdge(source, target)

    @_handle_exceptions
323
    @_lazy_load
324
325
326
327
328
    def remove_edge(self, edge):
        "Remove a edge from the graph"
        return self.__graph.RemoveEdge(edge)

    @_handle_exceptions
329
    @_lazy_load
330
331
332
333
334
335
    def __get_vertex_properties(self):
        return self.__graph.GetVertexProperties()
    vertex_properties = property(__get_vertex_properties,
                                 doc="Dictionary of vertex properties")

    @_handle_exceptions
336
    @_lazy_load
337
338
339
340
341
342
    def __get_edge_properties(self):
        return self.__graph.GetEdgeProperties()
    edge_properties = property(__get_edge_properties,
                                 doc="Dictionary of edge properties")

    @_handle_exceptions
343
    @_lazy_load
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    def __get_graph_properties(self):
        class GraphPropertyDict(dict):
            """Wrapper for the dict of graph properties, which sets the value on
            the property map when changed in the dict."""
            def __init__(self, g, old):
                dict.__init__(self)
                dict.update(self,old)
                self.g = g
            def __setitem__(self, key, val):
                g = self.g._Graph__graph
                try:
                    g.GetGraphProperties()[key][g] = val
                except KeyError:
                    raise
                except:
                    raise ValueError("wrong value for type '%s': '%s'" % \
                                     (g.GetGraphProperties()[key].get_type(),
                                      str(val)))
                dict.__setitem__(self, key, val)
            def __delitem__(self, key):
                g = self.g._Graph__graph
                g.RemoveGraphProperty(key)
                dict.__delitem__(self, key)
            def get_type(self, key):
                """Return the type of the internal property"""
                return self.g._Graph__graph.GetGraphProperties()[key].get_type()
        valdict = dict((k, v[self.__graph]) \
                       for k,v in self.__graph.GetGraphProperties().iteritems())
        return GraphPropertyDict(self, valdict)
373

374
    @_handle_exceptions
375
    @_lazy_load
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
    def __set_graph_properties(self, val):
        props = self.__graph.GetGraphProperties()
        for k,v in val.iteritems():
            if not props.has_key(k):
                if v.__class__ == str:
                    typename = "string"
                elif v.__class__ == float:
                    typename = "double"
                elif v.__class__ == int:
                    typename = "int"
                elif v.__class__ == bool:
                    typename = "boolean"
                else:
                    raise TypeError("invalid value type for graph " + \
                                    "property '%s'" % k)
                self.add_graph_property(k, typename)
                props = self.__graph.GetGraphProperties()
            props[k][self.__graph] = v
394

395
396
397
398
    graph_properties = property(__get_graph_properties, __set_graph_properties,
                                doc="Dictionary of graph properties")

    @_handle_exceptions
399
    @_lazy_load
400
401
402
403
404
405
406
    def add_vertex_property(self, name, type):
        """Add a new (uninitialized) vertex property map of type 'type', and
        return it"""
        self.edit_vertex_property(name, type)
        return self.vertex_properties[name]

    @_handle_exceptions
407
    @_lazy_load
408
409
410
411
    def add_edge_property(self, name, type):
        """Add a new (uninitialized) edge property map of type 'type', and
        return it"""
        self.edit_edge_property(name, type)
Tiago Peixoto's avatar
Tiago Peixoto committed
412
        return self.edge_properties[name]
413
414

    @_handle_exceptions
415
    @_lazy_load
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    def add_graph_property(self, name, type):
        """Add a new (uninitialized) graph property map of type 'type'"""
        self.edit_graph_property(name, type)

    # Basic options (File i/o and such)
    __groups = ["Basic Options"]

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
    def load(self, filename, format="auto"):
        """Load graph from 'filename'. The format is guessed from the file name,
        or can be specified by 'format', which can be either 'xml' or 'dot'."""

        if format == 'auto':
            self.__graph.ReadFromFile(filename)
        else:
            self.__graph.ReadFromFile(filename, format)
433
434
435
436
437
438
439
440
441
        self.lazy_filename = filename
        self.lazy_format = format

    @_handle_exceptions
    def lazy_load(self, filename, format="auto"):
        """Calls load() with the same arguments when the graph is first accessed."""

        self.lazy_filename = filename
        self.lazy_format = format
442
443
444

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
445
    @_lazy_load
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    def save(self, filename, format="auto"):
        """Save graph to file. The format is guessed from the 'file' name, or
        can be specified by 'format', which can be either 'xml' or 'dot'."""

        if format == 'auto':
            self.__graph.WriteToFile(filename)
        else:
            self.__graph.WriteToFile(filename, format)

    # Graph generation
    __groups.append("Graph generation")

    @_attrs(opt_group=__groups[-1], first_subopt="N")
    @_handle_exceptions
460
    @_lazy_load
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    def correlated_configurational_model \
            (self, N = 10000, pjk = "lambda j, k: 1.0",
             pjk_ceil = "lambda j, k: pjk(j, k)", pjk_m = 1.0,
             inv_pjk_ceil = "lambda p,r:(inv_poisson(p, 2), inv_poisson(p, 2))",
             corr = "lambda jl, kl, j, k: 1.0",
             corr_ceil = "lambda jl, kl, j, k: corr(jl,kl,j,k)", corr_m = 1.0,
             inv_corr_ceil = "lambda p, r, a, b: inv_pjk_ceil(p, r)",
             undirected = False, progress = False, seed = int(time.time())):
        """Generate graph using the configurational model with arbitrary degree
        correlations. See documentation for details."""

        f = self.__graph.GenerateCorrelatedConfigurationalModel
        exp_vars = dict()
        exp_vars["pjk"] = _eval_expr(pjk, exp_vars)
        exp_vars["pjk_ceil"] = _eval_expr(pjk_ceil, exp_vars)
        exp_vars["inv_pjk_ceil"] = _eval_expr(inv_pjk_ceil, exp_vars)
        exp_vars["corr"] = _eval_expr(corr, exp_vars)
        exp_vars["corr_ceil"] = _eval_expr(corr_ceil, exp_vars)
        exp_vars["inv_corr_ceil"] = _eval_expr(inv_corr_ceil, exp_vars)
        f(N, exp_vars["pjk"], exp_vars["pjk_ceil"], exp_vars["inv_pjk_ceil"],
          pjk_m, exp_vars["corr"], exp_vars["corr_ceil"],
          exp_vars["inv_corr_ceil"], corr_m, undirected, seed, progress)

    # Graph filtering
    __groups.append("Filtering")

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
489
    @_lazy_load
490
491
492
493
494
495
    def directed(self):
        """Treat graph as directed (default)."""
        self.__graph.SetDirected(True)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
496
    @_lazy_load
497
498
499
500
501
    def undirected(self):
        """Treat graph as undirected."""
        self.__graph.SetDirected(False)

    @_handle_exceptions
502
    @_lazy_load
503
504
505
506
507
    def set_directed(self, is_directed):
        """Set the directedness of the graph"""
        self.__graph.SetDirected(is_directed)

    @_handle_exceptions
508
    @_lazy_load
509
510
511
512
513
514
    def is_directed(self):
        """Get the directedness of the graph"""
        return self.__graph.GetDirected()

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
515
    @_lazy_load
516
517
518
519
520
    def reverse(self):
        """Reverse the direction of the edges."""
        self.__graph.SetReversed(not self.__graph.GetReversed())

    @_handle_exceptions
521
    @_lazy_load
522
    def set_reverse(self, is_reversed):
523
524
525
526
527
        """Reverse the direction of the edges, if 'reversed' is True, or
        maintain the original direction otherwise."""
        self.__graph.SetReversed(is_reversed)

    @_handle_exceptions
528
    @_lazy_load
529
530
531
532
533
534
    def get_reverse(self):
        """Return 'True' if the edges are reversed, and 'False' otherwise."""
        return self.__graph.GetReversed()

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
535
    @_lazy_load
536
537
538
539
540
541
542
543
    def exclude_vertex_range(self, property, range):
        """Choose vertex property and range to exclude."""
        (ran, inc, inverted) = _parse_range(range)
        self.__graph.SetVertexFilterProperty(property)
        self.__graph.SetVertexFilterRange(ran, inc, not inverted)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
544
    @_lazy_load
545
546
547
548
549
550
551
552
    def keep_vertex_range(self, property, range):
        """Choose vertex property and range to keep (and exclude the rest)."""
        (ran, inc, inverted) = _parse_range(range)
        self.__graph.SetVertexFilterProperty(property)
        self.__graph.SetVertexFilterRange(ran, inc, inverted)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
553
    @_lazy_load
554
555
556
557
558
559
    def reset_vertex_filter(self):
        """Remove edge filter."""
        self.__graph.SetVertexFilterProperty('')

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
560
    @_lazy_load
561
562
563
564
565
566
567
568
    def exclude_edge_range(self, property, range):
        """Choose edge property and range to exclude."""
        (ran, inc, inverted) = _parse_range(range)
        self.__graph.SetEdgeFilterProperty(property)
        self.__graph.SetEdgeFilterRange(ran, inc, not inverted)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
569
    @_lazy_load
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    def keep_edge_range(self, property, range):
        """Choose edge property and range to keep (and exclude the rest)."""
        (ran, inc, inverted) = _parse_range(range)
        self.__graph.SetEdgeFilterProperty(property)
        self.__graph.SetEdgeFilterRange(ran, inc, inverted)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
    def reset_edge_filter(self):
        """Remove edge filter"""
        self.__graph.SetEdgeFilterProperty('')

    # Graph modification
    __groups.append("Graph Modification")

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
587
    @_lazy_load
588
589
590
591
    def edit_vertex_property(self, property, type="double", expr=None):
        """Edit the selected vertex property"""
        self.__graph.EditVertexProperty(property, type,
                                        _eval_expr(expr,
592
                                                   edit_expr="v"), self)
593
594
595

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
596
    @_lazy_load
597
598
599
600
    def edit_edge_property(self, property, type="double", expr=None):
        """Edit the selected edge property"""
        self.__graph.EditEdgeProperty(property, type,
                                      _eval_expr(expr,
601
                                                 edit_expr="e"), self)
602
603
604

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
605
    @_lazy_load
606
607
608
609
    def edit_graph_property(self, property, type="double", expr=None):
        """Edit the selected graph property"""
        self.__graph.EditGraphProperty(property, type,
                                       _eval_expr(expr,
610
                                                  edit_expr="g"), self)
611
612
613

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
614
    @_lazy_load
615
616
617
618
619
620
    def remove_vertex_property(self, property):
        """Remove the selected vertex property"""
        self.__graph.RemoveVertexProperty(property)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
621
    @_lazy_load
622
623
624
625
626
627
    def remove_edge_property(self, property):
        """Remove the selected edge property"""
        self.__graph.RemoveEdgeProperty(property)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
628
    @_lazy_load
629
630
631
632
633
634
    def remove_graph_property(self, property):
        """Remove the selected graph property"""
        self.__graph.RemoveGraphProperty(property)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
635
    @_lazy_load
636
637
638
639
640
641
    def insert_vertex_index_property(self, property):
        """Insert vertex index as property"""
        self.__graph.InsertVertexIndexProperty(property)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
642
    @_lazy_load
643
644
645
646
647
648
    def insert_edge_index_property(self, property):
        """Insert edge index as property"""
        self.__graph.InsertEdgeIndexProperty(property)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
649
    @_lazy_load
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
    def list_properties(self):
        """List all properties"""
        w = max([len(x) for x in self.graph_properties.keys() + \
                 self.vertex_properties.keys() + \
                 self.edge_properties.keys()]) + 4
        w = w if w > 14 else 14
        for k,v in self.graph_properties.iteritems():
            print "%%-%ds (graph)   (type: %%s, val: %%s)" % w % \
                  (k, self.graph_properties.get_type(k), str(v))
        for k,v in self.vertex_properties.iteritems():
            print "%%-%ds (vertex)  (type: %%s)" % w % (k, v.get_type())
        for k,v in self.edge_properties.iteritems():
            print "%%-%ds (edge)    (type: %%s)" % w % (k, v.get_type())

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
666
    @_lazy_load
667
668
669
670
671
672
673
674
    def purge_vertices(self):
        """Remove all vertices of the graph which are currently being filtered
        out, and return to the unfiltered state"""
        self.__graph.PurgeVertices()
        self.__graph.SetVertexFilterProperty('')

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
675
    @_lazy_load
676
677
678
679
680
681
    def purge_edges(self):
        """Remove all edges of the graph which are currently being filtered out,
        and return to the unfiltered state"""
        self.__graph.PurgeEdges()
        self.__graph.SetEdgeFilterProperty('')

Tiago Peixoto's avatar
Tiago Peixoto committed
682
683
    @_attrs(opt_group=__groups[-1], fist_subopt="parallel_edges")
    @_handle_exceptions
684
    @_lazy_load
Tiago Peixoto's avatar
Tiago Peixoto committed
685
686
687
    @_limit_args({"strategy":["correlated", "uncorrelated"]})
    def random_rewire(self, strategy="uncorrelated", parallel_edges=False,
                      self_loops=False, seed=int(time.time())):
688
        """Randomly rewire the edges of the graph"""
Tiago Peixoto's avatar
Tiago Peixoto committed
689
690
        self.__graph.RandomRewire(strategy, self_loops, parallel_edges, seed)

691
692
693
694
695
    # Basic graph statistics
    __groups.append("Basic Statistics")

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
696
    @_lazy_load
697
698
699
700
701
702
    def number_of_vertices(self):
        """Get the number of vertices."""
        return self.__graph.GetNumberOfVertices()

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
703
    @_lazy_load
704
705
706
707
708
709
    def number_of_edges(self):
        """Get the number of edges"""
        return self.__graph.GetNumberOfEdges()

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
710
    @_lazy_load
711
712
713
714
715
716
    def vertex_histogram(self, degree):
        """Get the vertex degree/property histogram"""
        return self.__graph.GetVertexHistogram(_degree(degree))

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
717
    @_lazy_load
718
719
720
721
722
723
    def edge_histogram(self, property):
        """Get the edge property histogram"""
        return self.__graph.GetEdgeHistogram(property)

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
724
    @_lazy_load
725
726
727
728
729
730
    def average_vertex_property(self, degree):
        """Get the average of the vertex property"""
        return _get_mean(self.__graph.GetVertexHistogram(_degree(degree)))

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
731
    @_lazy_load
732
733
734
735
736
737
    def average_edge_property(self, property):
        """Get the average of the edge property"""
        return _get_mean(self.__graph.GetEdgeHistogram(property))

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
738
    @_lazy_load
739
740
741
742
743
744
745
746
    def combined_vertex_histogram(self, degree1, degree2):
        """Get the combined (degree1, degree2) histogram. Scalar properties are
        also accepted as degree1 or degree2"""
        return self.__graph.GetCombinedVertexHistogram(_degree(degree1),
                                                       _degree(degree2))

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
747
    @_lazy_load
748
749
750
751
752
753
754
755
    def distance_histogram(self, weight=None):
        """Get the distance histogram"""
        if weight == None:
            weight = ""
        self.__graph.GetDistanceHistogram(weight)

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
756
    @_lazy_load
757
758
759
760
761
762
763
764
    def average_distance(self, weight=None):
        """Get the averarge distance"""
        if weight == None:
            weight = ""
        return _get_mean(self.__graph.GetDistanceHistogram(weight))

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
765
    @_lazy_load
766
767
768
769
770
771
772
773
774
775
    def average_harmonic_distance(self, weight=None):
        """Get the averarge harmonic distance"""
        if weight == None:
            weight = ""
        hist = self.__graph.GetDistanceHistogram(weight)
        avg, err = _get_mean(dict((1.0/k, v) for k, v in hist.iteritems()))
        return (1.0/avg, err/(avg**2))

    @_attrs(opt_group=__groups[-1], fist_subopt="samples", has_output=True)
    @_handle_exceptions
776
    @_lazy_load
777
778
779
780
781
782
783
784
785
    def sampled_distance_histogram(self, samples=1000, weight=None,
                                   seed=int(time.time())):
        """Get the sampled distance histogram"""
        if weight == None:
            weight = ""
        return self.__graph.GetSampledDistanceHistogram(weight, samples, seed)

    @_attrs(opt_group=__groups[-1], has_output=True, first_subopt="samples")
    @_handle_exceptions
786
    @_lazy_load
787
788
789
790
791
792
793
794
795
796
797
    def average_sampled_distance(self, samples=1000, weight=None,
                                 seed=int(time.time())):
        """Get the average sampled distance."""
        if weight == None:
            weight = ""
        return _get_mean(self.__graph.GetSampledDistanceHistogram(weight,
                                                                  samples,
                                                                  seed))

    @_attrs(opt_group=__groups[-1], has_output=True, first_subopt="samples")
    @_handle_exceptions
798
    @_lazy_load
799
800
801
802
803
804
    def average_sampled_harmonic_distance(self, samples=1000, weight=None,
                                 seed=int(time.time())):
        """Get the average sampled harmonic distance."""
        if weight == None:
            weight = ""
        hist = self.__graph.GetSampledDistanceHistogram(weight, samples, seed)
805
        avg, err = _get_mean(dict([(1.0/k, v) for k, v in hist.iteritems()]))
806
807
808
809
        (1.0/avg, err/(avg**2))

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
810
    @_lazy_load
811
812
813
814
815
816
    def label_components(self, property):
        """Label components to property"""
        self.__graph.LabelComponents(property)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
817
    @_lazy_load
818
819
820
821
822
823
    def label_parallel_edges(self, property):
        """Label parallel edges to property"""
        self.__graph.LabelParallelEdges(property)

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
824
    @_lazy_load
825
826
827
828
829
830
    def reciprocity(self):
        """Get the edge reciprocity"""
        self.__graph.GetReciprocity()

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
831
    @_lazy_load
832
833
834
835
836
837
838
839
    def minimum_spanning_tree(self, property,  weight=None):
        """Mark the minimum spanning tree edges in property"""
        if weight == None:
            weight = ""
        self.__graph.GetMinimumSpanningTree(weight, property)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
840
    @_lazy_load
841
842
843
844
845
846
    def line_graph(self, file, format="xml"):
        """Save the corresponding line graph to file"""
        self.__graph.GetLineGraph(file, format)

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
847
    @_lazy_load
848
849
850
851
852
853
854
855
856
    def betweenness_centrality(self, vertex_betweeness, edge_betweeness,
                               weight=None):
        """Calculate and store the vertex and/or edge betweenness centrality"""
        if weight == None:
            weight = ""
        self.__graph.GetBetweenness(weight, edge_betweeness, vertex_betweeness)

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
857
    @_lazy_load
858
859
860
861
862
863
864
865
866
    def central_point_dominance(self, vertex_betweeness):
        """Calculate central point dominance, given the 'vertex_betweeness'
        vertex property"""
        return self.__graph.GetCentralPointDominance(vertex_betweeness)

    __groups.append("Correlations")

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
867
    @_lazy_load
868
869
870
    def average_combined_vertex_correlation(self, degree1, degree2):
        """Get the average of degree2 in function of degree1. Scalar properties
        are also accepted as degree1 or degree2"""
871
872
        f = self.__graph.GetAverageCombinedVertexCorrelation
        return f(_degree(degree1), _degree(degree2))
873
874
875

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
876
    @_lazy_load
877
878
879
880
881
882
883
    def vertex_correlation_histogram(self, origin_degree, neighbour_degree,
                                     weight=None):
        """Get the degree correlation histogram. Scalar properties are also
        accepted in place of *_degree. An optional edge weight property can be
        passed by weight"""
        if weight == None:
            weight = ""
884
885
        f = self.__graph.GetVertexCorrelationHistogram
        return f(_degree(origin_degree), _degree(neighbour_degree), weight)
886
887
888

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
889
    @_lazy_load
890
891
892
893
894
895
896
897
898
899
900
901
    def average_nearest_neighbours_correlation(self, origin_degree,
                                               neighbour_degree, weight=None):
        """Get the average nearest neighbours correlation. Scalar properties are
        also accepted in place of *_degree. An optional edge weight property can
        be passed by 'weight'"""
        if weight == None:
            weight = ""
        f = self.__graph.GetAverageNearestNeighboursCorrelation
        return f(_degree(origin_degree), _degree(neighbour_degree), weight)

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
902
    @_lazy_load
903
904
905
906
907
908
909
910
911
    def edge_vertex_correlation_histogram(self, degree_source, edge_prop,
                                          degree_target):
        """Get the source degree vs. edge scalar vs. target degree correlation
        histogram. Scalar properties are also accepted in place of degree_*"""
        f = self.__graph.GetEdgeVertexCorrelationHistogram
        return f(_degree(degree_source), edge_prop, _degree(degree_target))

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
912
    @_lazy_load
913
914
915
916
917
918
919
    def assortativity_coefficient(self, degree):
        """Get the assortativity coefficient. Scalar properties are also
        accepted in place of degree"""
        return self.__graph.GetAssortativityCoefficient(_degree(degree))

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
920
    @_lazy_load
921
922
923
924
925
926
927
928
929
    def scalar_assortativity_coefficient(self, degree):
        """Get the scalar assortativity coefficient. Scalar properties are also
        accepted in place of degree"""
        return self.__graph.GetScalarAssortativityCoefficient(_degree(degree))

    __groups.append("Clustering")

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
930
    @_lazy_load
931
932
933
934
935
936
    def local_clustering_coefficient(self, property):
        """Set the local clustering coefficient to vertex property"""
        self.__graph.SetLocalClusteringToProperty(property)

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
937
    @_lazy_load
938
939
940
941
942
943
    def global_clustering_coefficient(self, file):
        """Get the global clustering coefficient"""
        return self.__graph.GetGlobalClustering()

    @_attrs(opt_group=__groups[-1])
    @_handle_exceptions
944
    @_lazy_load
945
946
947
948
949
950
951
952
953
    def extended_clustering_coefficient(self, prefix, max):
        """Set the extended clustering coefficients c1 to cmax to vertex
        properties prefix1 to prefixmax"""
        self.__graph.SetExtendedClusteringToProperty(prefix, max)

    __groups.append("Layout")

    @_attrs(opt_group=__groups[-1], first_subopt="type")
    @_handle_exceptions
954
    @_lazy_load
955
956
957
958
959
960
961
962
963
964
965
966
    @_limit_args({"type":["fg-all-pairs", "fg-grid", "kw"]})
    def spring_block_layout(self, property, type="fg-all-pairs", iter=1000,
                            weight=None, seed=int(time.time())):
        """Compute the spring block layout. The positions will be stored in
        property."""
        if weight == None:
            weight = ""
        self.__graph.ComputeGraphLayoutSpringBlock(property, weight, type, iter,
                                                   seed)

    @_attrs(opt_group=__groups[-1], first_subopt="type")
    @_handle_exceptions
967
    @_lazy_load
968
969
970
971
972
973
974
975
976
977
978
979
    @_limit_args({"type":["square", "circle", "heart"]})
    def gursoy_atun_layout(self, property, type="square", iter=1000,
                           weight=None, seed=int(time.time())):
        """Compute the Gursoy-Atun layout."""
        if weight == None:
            weight = ""
        self.__graph.ComputeGraphLayoutGursoy(property, weight,type, iter, seed)

    __groups.append("Community")

    @_attrs(opt_group=__groups[-1], first_subopt="g")
    @_handle_exceptions
980
    @_lazy_load
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
    @_limit_args({"corr":["correlated", "uncorrelated", "random"]})
    def community_structure(self, property, g=1.0, n=1000, tmin=0.01, tmax=1.0,
                            spins=0, corr="uncorrelated", weight=None,
                            seed=int(time.time()), verbose=False, history=""):
        """Calculate the community structure and assign it to property."""
        strat_map = {'correlated': libgraph_tool.CommCorr.Correlated,
                     'uncorrelated': libgraph_tool.CommCorr.Uncorrelated,
                     'random': libgraph_tool.CommCorr.ErdosReyni}
        if weight == None:
            weight = ""
        self.__graph.GetCommunityStructure(g, strat_map[correlated], n, tmin,
                                           tmax, spins, seed, verbose, history,
                                           weight, property)

    @_attrs(opt_group=__groups[-1], has_output=True)
    @_handle_exceptions
997
    @_lazy_load
998
999
1000
    def modularity(self, property, weight=None):
        """Calculate the modularity, given a community partition specified by
        property"""