core.py 47.7 KB
Newer Older
1
#! /usr/bin/env python
2
3
# -*- coding: utf-8 -*-
#
4
# graph_tool -- a general graph manipulation python module
5
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2007-2010 Tiago de Paula Peixoto <tiago@skewed.de>
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# 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/>.

Tiago Peixoto's avatar
Tiago Peixoto committed
21
22
from dl_import import *
dl_import("import libgraph_tool_core as libcore")
Tiago Peixoto's avatar
Tiago Peixoto committed
23
import libgraph_tool_core as libcore   # for pylint
24
__version__ = libcore.mod_info().version
25

Tiago Peixoto's avatar
Tiago Peixoto committed
26
import io  # sets up libcore io routines
27

Tiago Peixoto's avatar
Tiago Peixoto committed
28
29
import sys
import os, os.path, re, struct, fcntl, termios, gzip, bz2, string,\
30
       textwrap, time, signal, traceback, shutil, time, math, inspect, \
31
       functools, types, weakref, copy
32
from StringIO import StringIO
Tiago Peixoto's avatar
Tiago Peixoto committed
33
from decorators import _wraps, _require, _attrs, _limit_args
34
35
from inspect import ismethod
import numpy
36
37
38
39
40

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

Tiago Peixoto's avatar
Tiago Peixoto committed
41

42
def _prop(t, g, prop):
43
44
    """Return either a property map, or an internal property map with a given
    name."""
45
46
    if type(prop) == str:
        try:
Tiago Peixoto's avatar
Tiago Peixoto committed
47
            pmap = g.properties[(t, prop)]
48
        except KeyError:
Tiago Peixoto's avatar
Tiago Peixoto committed
49
50
51
            raise KeyError("no internal %s property named: %s" %\
                           ("vertex" if t == "v" else \
                            ("edge" if t == "e" else "graph"), prop))
52
53
    else:
        pmap = prop
54
55
56
    if pmap == None:
        return libcore.any()
    else:
57
        if t != prop.key_type():
Tiago Peixoto's avatar
Tiago Peixoto committed
58
            names = {'e': 'edge', 'v': 'vertex', 'g': 'graph'}
59
60
            raise ValueError("Expected '%s' property map, got '%s'" %
                             (names[t], names[prop.key_type()]))
61
62
        return pmap._PropertyMap__map.get_map()

Tiago Peixoto's avatar
Tiago Peixoto committed
63

64
65
def _degree(g, name):
    """Retrieve the degree type from string, or returns the corresponding
66
    property map."""
67
68
69
70
71
72
73
74
75
76
    deg = name
    if name == "in-degree" or name == "in":
        deg = libcore.Degree.In
    elif name == "out-degree" or name == "out":
        deg = libcore.Degree.Out
    elif name == "total-degree" or name == "total":
        deg = libcore.Degree.Total
    else:
        deg = _prop("v", g, deg)
    return deg
77

Tiago Peixoto's avatar
Tiago Peixoto committed
78

79
def _type_alias(type_name):
Tiago Peixoto's avatar
Tiago Peixoto committed
80
81
82
83
84
85
    alias = {"int8_t": "bool",
             "boolean": "bool",
             "int": "int32_t",
             "long": "int32_t",
             "long long": "int64_t",
             "object": "python::object"}
86
87
    if type_name in value_types():
        return type_name
Tiago Peixoto's avatar
Tiago Peixoto committed
88
    if type_name in alias:
89
        return alias[type_name]
90
    ma = re.compile(r"vector<(.*)>").match(type_name)
91
92
    if ma:
        t = ma.group(1)
Tiago Peixoto's avatar
Tiago Peixoto committed
93
        if t in alias:
94
95
96
            return "vector<%s>" % alias[t]
    raise ValueError("invalid property value type: " + type_name)

Tiago Peixoto's avatar
Tiago Peixoto committed
97

Tiago Peixoto's avatar
Tiago Peixoto committed
98
def show_config():
99
    """Show ``graph_tool`` build configuration."""
Tiago Peixoto's avatar
Tiago Peixoto committed
100
101
102
103
104
105
106
107
108
    info = libcore.mod_info()
    print "version:", info.version
    print "gcc version:", info.gcc_version
    print "compilation flags:", info.cxxflags
    print "install prefix:", info.install_prefix
    print "python dir:", info.python_dir
    print "graph filtering:", libcore.graph_filtering_enabled()
    print "openmp:", libcore.openmp_enabled()
    print "uname:", " ".join(os.uname())
109

110
################################################################################
111
# Property Maps
112
113
################################################################################

Tiago Peixoto's avatar
Tiago Peixoto committed
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
class PropertyArray(numpy.ndarray):
    """This is a :class:`~numpy.ndarray` subclass which keeps a reference of its :class:`~graph_tool.PropertyMap` owner, and detects if the underlying data has been invalidated."""

    __array_priority__ = -10

    def _get_pmap(self):
        return self._prop_map

    def _set_pmap(self, value):
        self._prop_map = value

    prop_map = property(_get_pmap, _set_pmap,
                        doc=":class:`~graph_tool.PropertyMap` owner instance.")

    def __new__(cls, input_array, prop_map):
        obj = numpy.asarray(input_array).view(cls)
        obj.prop_map = prop_map

        # check if data really belongs to property map
        if (prop_map._get_data().__array_interface__['data'][0] !=
            obj._get_base_data()):
            obj.prop_map = None
            obj = numpy.asarray(obj)

        return obj

    def _get_base(self):
        base = self
        while base.base is not None:
            base = base.base
        return base
Tiago Peixoto's avatar
Tiago Peixoto committed
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
    def _get_base_data(self):
        return self._get_base().__array_interface__['data'][0]

    def _check_data(self):
        if self.prop_map is None:
            return

        data = self.prop_map._get_data()

        if (data is None or
            data.__array_interface__['data'][0] != self._get_base_data()):
            raise ValueError(("The graph correspondig to the underlying" +
                              " property map %s has changed. The" +
                              " PropertyArray at 0x%x is no longer valid!") %
                             (repr(self.prop_map), id(self)))

    def __array_finalize__(self, obj):
        if type(obj) is PropertyArray:
            obj._check_data()

        if obj is not None:
            # inherit prop_map only if the data is the same
            if (type(obj) is PropertyArray and
                self._get_base_data() == obj._get_base_data()):
                self.prop_map = getattr(obj, 'prop_map', None)
            else:
                self.prop_map = None
        self._check_data()

    def __array_prepare__(self, out_arr, context=None):
        self._check_data()
        return numpy.ndarray.__array_prepare__(self, out_arr, context)

    def __array_wrap__(self, out_arr, context=None):
        #demote to ndarray
        obj = numpy.ndarray.__array_wrap__(self, out_arr, context)
        return numpy.asarray(obj)

    # Overload members and operators to add data checking

    def _wrap_method(method):
        method = getattr(numpy.ndarray, method)

        def checked_method(self, *args, **kwargs):
            self._check_data()
            return method(self, *args, **kwargs)

        if ismethod(method):
            checked_method = _wraps(method)(checked_method)
        checked_method.__doc__ = getattr(method, "__doc__", None)
        return checked_method

    for method in ['all', 'any', 'argmax', 'argmin', 'argsort', 'astype',
                   'byteswap', 'choose', 'clip', 'compress', 'conj',
                   'conjugate', 'copy', 'cumprod', 'cumsum', 'diagonal', 'dot',
                   'dump', 'dumps', 'fill', 'flat', 'flatten', 'getfield',
                   'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min',
                   'newbyteorder', 'nonzero', 'prod', 'ptp', 'put', 'ravel',
                   'real', 'repeat', 'reshape', 'resize', 'round',
                   'searchsorted', 'setfield', 'setflags', 'sort', 'squeeze',
                   'std', 'sum', 'swapaxes', 'take', 'tofile', 'tolist',
                   'tostring', 'trace', 'transpose', 'var', 'view',
                   '__getitem__']:
        locals()[method] = _wrap_method(method)


class PropertyMap(object):
    """This class provides a mapping from vertices, edges or whole graphs to
Tiago Peixoto's avatar
Tiago Peixoto committed
215
216
217
218
219
220
221
222
223
224
    arbitrary properties.

    The possible property types are listed below.

    .. table::

        =======================     ================
         Type name                  Alias
        =======================     ================
        ``bool``                    ``uint8_t``
225
226
        ``int32_t``                 ``int``
        ``int64_t``                 ``long``
Tiago Peixoto's avatar
Tiago Peixoto committed
227
        ``double``                  ``float``
228
229
        ``long double``
        ``string``
Tiago Peixoto's avatar
Tiago Peixoto committed
230
231
232
233
234
235
        ``vector<bool>``            ``vector<uint8_t>``
        ``vector<int32_t>``         ``vector<int>``
        ``vector<int64_t>``         ``vector<long>``
        ``vector<double>``          ``vector<float>``
        ``vector<long double>``
        ``vector<string>``
236
        ``python::object``          ``object``
Tiago Peixoto's avatar
Tiago Peixoto committed
237
238
        =======================     ================
    """
Tiago Peixoto's avatar
Tiago Peixoto committed
239
    def __init__(self, pmap, g, key_type, key_trans=None):
240
        self.__map = pmap
241
        self.__g = weakref.ref(g)
242
243
244
245
246
        self.__key_type = key_type
        self.__key_trans = key_trans if key_trans != None else lambda k: k
        self.__register_map()

    def __register_map(self):
247
248
249
250
        if self.__g() == None:
            return
        self.__g()._Graph__known_properties.append((self.key_type(),
                                                    weakref.ref(self.__map)))
Tiago Peixoto's avatar
Tiago Peixoto committed
251

252
    def __unregister_map(self):
253
254
255
256
257
        if self.__g() == None:
            return
        i = self.__g()._Graph__known_properties.index((self.key_type(),
                                                       weakref.ref(self.__map)))
        del self.__g()._Graph__known_properties[i]
258
259
260
261
262
263
264
265
266
267

    def __del__(self):
        self.__unregister_map()

    def __getitem__(self, k):
        return self.__map[self.__key_trans(k)]

    def __setitem__(self, k, v):
        self.__map[self.__key_trans(k)] = v

268
269
270
271
    def __repr__(self):
        # provide some more useful information
        if self.key_type() == "e":
            k = "Edge"
Tiago Peixoto's avatar
Tiago Peixoto committed
272
        elif self.key_type() == "v":
273
274
275
276
277
278
279
280
281
282
283
            k = "Vertex"
        else:
            k = "Graph"
        g = self.__g()
        if g == None:
            g = "a non-existent graph"
        else:
            g = "Graph 0x%x" % id(g)
        return ("<PropertyMap object with key type '%s' and value type '%s',"
                + " for %s, at 0x%x>") % (k, self.value_type(), g, id(self))

284
    def get_graph(self):
285
        """Get the graph class to which the map refers."""
286
        return self.__g()
287
288

    def key_type(self):
289
        """Return the key type of the map. Either 'g', 'v' or 'e'."""
290
291
292
        return self.__key_type

    def value_type(self):
293
        """Return the value type of the map."""
294
295
        return self.__map.value_type()

296
    def get_array(self):
297
        """Get a :class:`~graph_tool.PropertyArray` with the property values.
298
299
300
301

        .. WARNING::

           The returned array does not own the data, which belongs to the
302
303
304
305
           property map. Therefore, if the graph changes, the array may become
           *invalid* and any operation on it will fail with a
           :class:`ValueError` exception. Do **not** store the array if
           the graph is to be modified; store a **copy** instead.
306
        """
307
308
309
310
311
312
        a = self._get_data()
        return PropertyArray(a, prop_map=self)

    def _get_data(self):
        if self.__g() is None:
            return None
313
        self.__g().stash_filter(edge=True, vertex=True)
314
315
316
        if self.__key_type == 'v':
            n = self.__g().num_vertices()
        elif self.__key_type == 'e':
317
            n = self.__g()._Graph__graph.GetMaxEdgeIndex() + 1
318
319
        else:
            n = 1
320
        self.__g().pop_filter(edge=True, vertex=True)
321
322
        a = self.__map.get_array(n)
        return a
323

Tiago Peixoto's avatar
Tiago Peixoto committed
324
    def __get_array(self):
325
326
327
328
        if self.get_array() != None:
            return self.get_array()[:]
        else:
            return None
Tiago Peixoto's avatar
Tiago Peixoto committed
329
330
331
332
333
334
335

    def __set_array(self, v):
        self.get_array()[:] = v

    a = property(__get_array, __set_array,
                 doc=r"""Shortcut to the :meth:`~PropertyMap.get_array` method
                 as a property. A view to the array is returned, instead of the
336
                 array itself, for convenience.""")
Tiago Peixoto's avatar
Tiago Peixoto committed
337

338
339
340
341
    def is_writable(self):
        """Return True if the property is writable."""
        return self.__map.is_writable()

Tiago Peixoto's avatar
Tiago Peixoto committed
342

343
344
345
346
347
def _check_prop_writable(prop, name=None):
    if not prop.is_writable():
        raise ValueError("property map%s is not writable." %\
                         ((" '%s'" % name) if name != None else ""))

Tiago Peixoto's avatar
Tiago Peixoto committed
348

349
350
351
352
353
354
355
356
357
358
359
def _check_prop_scalar(prop, name=None, floating=False):
    scalars = ["bool", "int32_t", "int64_t", "unsigned long",
               "double", "long double"]
    if floating:
        scalars = ["double", "long double"]

    if prop.value_type() not in scalars:
        raise ValueError("property map%s is not of scalar%s type." %\
                         (((" '%s'" % name) if name != None else ""),
                          (" floating" if floating else "")))

Tiago Peixoto's avatar
Tiago Peixoto committed
360

361
def _check_prop_vector(prop, name=None, scalar=True, floating=False):
362
363
    scalars = ["bool", "int32_t", "int64_t", "unsigned long",
               "double", "long double"]
364
365
    if not scalar:
        scalars += ["string"]
366
367
368
369
370
371
372
373
    if floating:
        scalars = ["double", "long double"]
    vals = ["vector<%s>" % v for v in scalars]
    if prop.value_type() not in vals:
        raise ValueError("property map%s is not of vector%s type." %\
                         (((" '%s'" % name) if name != None else ""),
                          (" floating" if floating else "")))

Tiago Peixoto's avatar
Tiago Peixoto committed
374

Tiago Peixoto's avatar
Tiago Peixoto committed
375
def group_vector_property(props, value_type=None, vprop=None, pos=None):
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
    """Group list of properties ``props`` into a vector property map of the same
    type.

    Parameters
    ----------
    props : list of :class:`~graph_tool.PropertyMap`
        Properties to be grouped.
    value_type : string (optional, default: None)
        If supplied, defines the value type of the grouped property.
    vprop : :class:`~graph_tool.PropertyMap` (optional, default: None)
        If supplied, the properties are grouped into this property map.
    pos : list of ints (optional, default: None)
        If supplied, should contain a list of indexes where each corresponding
        element of ``props`` should be inserted.

    Returns
    -------
    vprop : :class:`~graph_tool.PropertyMap`
       A vector property map with the grouped values of each property map in
       ``props``.
    """
397
    g = props[0].get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
398
    vtypes = set()
399
    keys = set()
Tiago Peixoto's avatar
Tiago Peixoto committed
400
    for i, p in enumerate(props):
401
402
403
        if "vector" in p.value_type():
            raise ValueError("property map 'props[%d]' is a vector property." %
                             i)
Tiago Peixoto's avatar
Tiago Peixoto committed
404
        vtypes.add(p.value_type())
405
406
        keys.add(p.key_type())
    if len(keys) > 1:
Tiago Peixoto's avatar
Tiago Peixoto committed
407
        raise ValueError("'props' must be of the same key type.")
408
409
410
    k = keys.pop()

    if vprop == None:
Tiago Peixoto's avatar
Tiago Peixoto committed
411
412
        if value_type == None and len(vtypes) == 1:
            value_type = vtypes.pop()
413
414
415
416
417
418
419
420
421
422
423
424

        if value_type != None:
            value_type = "vector<%s>" % value_type
            if k == 'v':
                vprop = g.new_vertex_property(value_type)
            elif k == 'e':
                vprop = g.new_edge_property(value_type)
            else:
                vprop = g.new_graph_property(value_type)
        else:
            ValueError("Can't automatically determine property map value" +
                       " type. Please provide the 'value_type' parameter.")
425
    _check_prop_vector(vprop, name="vprop", scalar=False)
426

Tiago Peixoto's avatar
Tiago Peixoto committed
427
    for i, p in enumerate(props):
428
429
430
431
432
433
434
435
436
437
438
439
440
441
        if k != "g":
            g.stash_filter(directed=True, reversed=True)
            g.set_directed(True)
            g.set_reversed(False)
            libcore.group_vector_property(g._Graph__graph,
                                          _prop(k, g, vprop),
                                          _prop(k, g, p),
                                          i if pos == None else pos[i],
                                          k == 'e')
            g.pop_filter(directed=True, reversed=True)
        else:
            vprop[g][i if pos == None else pos[i]] = p[g]
    return vprop

Tiago Peixoto's avatar
Tiago Peixoto committed
442

443
def ungroup_vector_property(vprop, pos, props=None):
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
    """Ungroup vector property map ``vprop`` into a list of individual property
    maps.

    Parameters
    ----------
    vprop : :class:`~graph_tool.PropertyMap`
        Vector property map to be ungrouped.
    pos : list of ints (optional, default: None)
        If supplied, should contain a list of indexes where each corresponding
        element of ``vprop`` should be inserted into the ``props`` list.
    props : list of :class:`~graph_tool.PropertyMap`  (optional, default: None)
        If supplied, should contain a list of property maps to which ``vprop``
        should be ungroupped.

    Returns
    -------
    props : list of :class:`~graph_tool.PropertyMap`
       A list of property maps with the ungrouped values of ``vprop``.
    """

464
    g = vprop.get_graph()
465
    _check_prop_vector(vprop, name="vprop", scalar=False)
466
467
468
469
470
471
472
473
474
475
    k = vprop.key_type()
    value_type = vprop.value_type().split("<")[1].split(">")[0]
    if props == None:
        if k == 'v':
            props = [g.new_vertex_property(value_type) for i in pos]
        elif k == 'e':
            props = [g.new_edge_property(value_type) for i in pos]
        else:
            props = [g.new_graph_property(value_type) for i in pos]

Tiago Peixoto's avatar
Tiago Peixoto committed
476
    for i, p in enumerate(pos):
477
478
479
480
481
482
483
484
485
486
        if props[i].key_type() != k:
            raise ValueError("'props' must be of the same key type as 'vprop'.")

        if k != 'g':
            g.stash_filter(directed=True, reversed=True)
            g.set_directed(True)
            g.set_reversed(False)
            libcore.ungroup_vector_property(g._Graph__graph,
                                            _prop(k, g, vprop),
                                            _prop(k, g, props[i]),
Tiago Peixoto's avatar
Tiago Peixoto committed
487
                                            p, k == 'e')
488
489
490
            g.pop_filter(directed=True, reversed=True)
        else:
            if len(vprop[g]) <= pos[i]:
Tiago Peixoto's avatar
Tiago Peixoto committed
491
                vprop[g].resize(pos[i] + 1)
492
493
            props[i][g] = vprop[g][pos[i]]
    return props
494

Tiago Peixoto's avatar
Tiago Peixoto committed
495

496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
class PropertyDict(dict):
    """Wrapper for the dict of vertex, graph or edge properties, which sets the
    value on the property map when changed in the dict."""
    def __init__(self, g, old, get_func, set_func, del_func):
        dict.__init__(self)
        dict.update(self, old)
        self.g = g
        self.get_func = get_func
        self.set_func = set_func
        self.del_func = del_func

    def __setitem__(self, key, val):
        if self.set_func != None:
            self.set_func(self.g, key, val)
        else:
            raise KeyError("Property dict cannot be set")
        dict.__setitem__(self, key, val)

    def __delitem__(self, key):
        self.del_func(self.g, key)
        dict.__delitem__(self, key)
517
518
519
520
521
522

################################################################################
# Graph class
# The main graph interface
################################################################################

Tiago Peixoto's avatar
Tiago Peixoto committed
523
524
525
from libgraph_tool_core import Vertex, Edge, Vector_bool, Vector_int32_t, \
     Vector_int64_t, Vector_double, Vector_long_double, Vector_string, \
     new_vertex_property, new_edge_property, new_graph_property
526

Tiago Peixoto's avatar
Tiago Peixoto committed
527

528
class Graph(object):
Tiago Peixoto's avatar
Tiago Peixoto committed
529
530
531
    """Generic multigraph class.

    This class encapsulates either a directed multigraph (default or if
532
533
    ``directed=True``) or an undirected multigraph (if ``directed=False``), with
    optional internal edge, vertex or graph properties.
534

Tiago Peixoto's avatar
Tiago Peixoto committed
535
536
537
538
539
540
541
542
    If ``g`` is specified, the graph (and its internal properties) will be
    copied.

    The graph is implemented as an `adjacency list`_, where both vertex and edge
    lists are C++ STL vectors.

    .. _adjacency list: http://en.wikipedia.org/wiki/Adjacency_list

543
    """
544

Tiago Peixoto's avatar
Tiago Peixoto committed
545
    def __init__(self, g=None, directed=True):
546
547
        """Construct a graph. If ``g`` is specified, the graph (and its internal
        properties) will be copied. The ``directed`` parameter specifies whether
548
        the graph should be directed or undirected."""
549
550
551
        self.__properties = {}
        self.__known_properties = []
        self.__filter_state = {"reversed": False,
Tiago Peixoto's avatar
Tiago Peixoto committed
552
553
554
                               "edge_filter": (None, False),
                               "vertex_filter": (None, False),
                               "directed": True}
555
556
        self.__stashed_filter_state = []

557
        if g == None:
558
            self.__graph = libcore.GraphInterface()
559
            self.set_directed(directed)
560
        else:
561
            self.__graph = libcore.GraphInterface(g.__graph)
Tiago Peixoto's avatar
Tiago Peixoto committed
562
            for k, v in g.__properties.iteritems():
563
564
                new_p = self.new_property(v.key_type(), v.value_type())
                self.copy_property(v, new_p, g)
565
                self.properties[k] = new_p
Tiago Peixoto's avatar
Tiago Peixoto committed
566
567
568

            self.__stashed_filter_state = [self.get_filter_state()]

569
570
571
572
573
574
575
            v_filt, v_rev = g.__filter_state["vertex_filter"]
            if v_filt != None:
                if v_filt not in g.vertex_properties.values():
                    new_filt = self.new_vertex_property("bool")
                    self.copy_property(v_filt, new_filt)

                else:
Tiago Peixoto's avatar
Tiago Peixoto committed
576
                    for k, v in g.vertex_properties.iteritems():
577
578
579
580
581
582
583
584
585
586
587
                        if v == v_filt:
                            new_filt = self.vertex_properties[k]
                self.__stashed_filter_state[0]["vertex_filter"] = (new_filt,
                                                                   v_rev)
            e_filt, e_rev = g.__filter_state["edge_filter"]
            if e_filt != None:
                if e_filt not in g.edge_properties.values():
                    new_filt = self.new_edge_property("bool")
                    self.copy_property(e_filt, new_filt)

                else:
Tiago Peixoto's avatar
Tiago Peixoto committed
588
                    for k, v in g.edge_properties.iteritems():
589
590
591
592
593
                        if v == e_filt:
                            new_filt = self.edge_properties[k]
                self.__stashed_filter_state[0]["edge_filter"] = (new_filt,
                                                                 e_rev)
            self.pop_filter()
594
595
596
597
598
        # internal index maps
        self.__vertex_index = \
                 PropertyMap(libcore.get_vertex_index(self.__graph), self, "v")
        self.__edge_index = \
                 PropertyMap(libcore.get_edge_index(self.__graph), self, "e")
599
600

    def copy(self):
601
        """Return a deep copy of self. All internal property maps are also
602
603
        copied."""
        return Graph(self)
604

605
606
607
608
609
610
611
612
613
614
615
    def __repr__(self):
        # provide some more useful information
        d = "directed" if self.is_directed() else "undirected"
        fr = ", reversed" if self.is_reversed() and self.is_directed() else ""
        f = ""
        if self.get_edge_filter()[0] != None:
            f += ", edges filtered by %s" % (str(self.get_edge_filter()))
        if self.get_vertex_filter()[0] != None:
            f += ", vertices filtered by %s" % (str(self.get_vertex_filter()))
        n = self.num_vertices()
        e = self.num_edges()
616
        return "<Graph object, %s%s, with %d %s and %d edge%s%s at 0x%x>"\
617
618
619
               % (d, fr, n, "vertex" if n == 1 else "vertices", e,
                  "" if e == 1 else "s", f, id(self))

620
    # Graph access
621
    # ============
622
623

    def vertices(self):
624
        """Return an iterator over the vertices.
625
626
627
628
629
630
631
632
633
634
635
636

        Examples
        --------
        >>> g = gt.Graph()
        >>> vlist = g.add_vertex(5)
        >>> vlist2 = []
        >>> for v in g.vertices():
        ...     vlist2.append(v)
        ...
        >>> assert(vlist == vlist2)

        """
637
        return libcore.get_vertices(weakref.ref(self.__graph))
638

639
640
641
642
643
644
645
    def vertex(self, i, use_index=False):
        """Return the i-th vertex from the graph. If use_index=True, the vertex
        with index i is returned (which can differ from the i-th vertex in case
        of filtered graphs)."""
        if use_index:
            self.stash_filter(vertex=True)
        try:
Tiago Peixoto's avatar
Tiago Peixoto committed
646
            v = libcore.get_vertex(weakref.ref(self.__graph), int(i))
647
648
649
650
        finally:
            if use_index:
                self.pop_filter(vertex=True)
        return v
651
652

    def edges(self):
653
        """Return an iterator over the edges."""
654
        return libcore.get_edges(weakref.ref(self.__graph))
655

656
    def add_vertex(self, n=1):
657
658
        """Add a vertex to the graph, and return it. If ``n > 1``, ``n``
        vertices are inserted and a list is returned."""
659
        vlist = [libcore.add_vertex(weakref.ref(self.__graph)) \
Tiago Peixoto's avatar
Tiago Peixoto committed
660
                 for i in xrange(0, n)]
661
        if n == 1:
662
663
            return vlist[0]
        return vlist
664

665
    def remove_vertex(self, vertex):
666
        """Remove a vertex from the graph."""
667
668
        index = self.vertex_index[vertex]
        for pmap in self.__known_properties:
669
670
671
            if pmap[0] == "v" and pmap[1]() != None and \
                   pmap[1]() != self.__vertex_index._PropertyMap__map:
                self.__graph.ShiftVertexProperty(pmap[1]().get_map(), index)
672
        self.clear_vertex(vertex)
673
        libcore.remove_vertex(self.__graph, vertex)
674

675
    def remove_vertex_if(self, predicate):
676
677
        """Remove all the vertices from the graph for which ``predicate(v)``
        evaluates to ``True``. """
678
679
680
681
682
683
        N = self.num_vertices()
        for i in xrange(0, N):
            v = self.vertex(N - i - 1)
            if predicate(v):
                self.remove_vertex(v)

684
    def clear_vertex(self, vertex):
685
        """Remove all in and out-edges from the given vertex."""
686
        del_es = set()
687
        for e in vertex.all_edges():
688
            del_es.add(e)
689
690
691
        for e in del_es:
            self.remove_edge(e)

692
    def add_edge(self, source, target):
693
        """Add a new edge from ``source`` to ``target`` to the graph, and return
694
        it."""
695
        return libcore.add_edge(weakref.ref(self.__graph), source, target)
696

697
    def remove_edge(self, edge):
698
        """Remove an edge from the graph."""
699
        return libcore.remove_edge(self.__graph, edge)
700

701
    def remove_edge_if(self, predicate):
702
703
        """Remove all edges from the graph, for which ``predicate(e)`` evaluates
        to ``True``."""
704
705
706
707
708
709
710
711
        for v in self.vertices():
            del_es = []
            for e in v.out_edges():
                if predicate(e):
                    del_es.append(e)
            for e in del_es:
                self.remove_edge(e)

712
    def clear(self):
713
        """Remove all vertices and edges from the graph."""
714
715
        self.__graph.Clear()

716
    def clear_edges(self):
717
        """Remove all edges from the graph."""
718
719
720
721
722
723
724
725
        self.__graph.ClearEdges()

    # Internal property maps
    # ======================

    # all properties
    def __get_properties(self):
        return PropertyDict(self, self.__properties,
Tiago Peixoto's avatar
Tiago Peixoto committed
726
727
728
                            lambda g, k: g.__properties[k],
                            lambda g, k, v: g.__set_property(k[0], k[1], v),
                            lambda g, k: g.__del_property(k[0], k[1]))
729

Tiago Peixoto's avatar
Tiago Peixoto committed
730
    @_limit_args({"t": ["v", "e", "g"]})
731
732
733
734
735
    @_require("k", str)
    @_require("v", PropertyMap)
    def __set_property(self, t, k, v):
        if t != v.key_type():
            raise ValueError("wrong key type for property map")
Tiago Peixoto's avatar
Tiago Peixoto committed
736
        self.__properties[(t, k)] = v
737

Tiago Peixoto's avatar
Tiago Peixoto committed
738
    @_limit_args({"t": ["v", "e", "g"]})
739
740
    @_require("k", str)
    def __del_property(self, t, k):
Tiago Peixoto's avatar
Tiago Peixoto committed
741
        del self.__properties[(t, k)]
742
743

    properties = property(__get_properties,
744
745
746
747
748
749
750
751
752
753
754
755
                          doc=
    """Dictionary of internal properties. Keys must always be a tuple, where the
    first element if a string from the set {'v', 'e', 'g'}, representing a
    vertex, edge or graph property, and the second element is the name of the
    property map.

    Examples
    --------
    >>> g = gt.Graph()
    >>> g.properties[("e", "foo")] = g.new_edge_property("vector<double>")
    >>> del g.properties[("e", "foo")]
    """)
756
757

    def __get_specific_properties(self, t):
Tiago Peixoto's avatar
Tiago Peixoto committed
758
        props = dict([(k[1], v) for k,v in self.__properties.iteritems() \
759
760
761
762
                      if k[0] == t ])
        return props

    # vertex properties
763
    def __get_vertex_properties(self):
764
        return PropertyDict(self, self.__get_specific_properties("v"),
Tiago Peixoto's avatar
Tiago Peixoto committed
765
766
767
                            lambda g, k: g.__properties[("v", k)],
                            lambda g, k, v: g.__set_property("v", k, v),
                            lambda g, k: g.__del_property("v", k))
768
769
    vertex_properties = property(__get_vertex_properties,
                                 doc="Dictionary of vertex properties")
Tiago Peixoto's avatar
Tiago Peixoto committed
770

771
    # edge properties
772
    def __get_edge_properties(self):
773
        return PropertyDict(self, self.__get_specific_properties("e"),
Tiago Peixoto's avatar
Tiago Peixoto committed
774
775
776
                            lambda g, k: g.__properties[("e", k)],
                            lambda g, k, v: g.__set_property("e", k, v),
                            lambda g, k: g.__del_property("e", k))
777
778
779
    edge_properties = property(__get_edge_properties,
                                 doc="Dictionary of edge properties")

780
    # graph properties
781
    def __get_graph_properties(self):
782
        return PropertyDict(self, self.__get_specific_properties("g"),
Tiago Peixoto's avatar
Tiago Peixoto committed
783
784
785
                            lambda g, k: g.__properties[("g", k)],
                            lambda g, k, v: g.__set_property("g", k, v),
                            lambda g, k: g.__del_property("g", k))
786
787
788
789
    graph_properties = property(__get_graph_properties,
                                 doc="Dictionary of graph properties")

    def list_properties(self):
790
        """List all internal properties.
791
792
793
794
795
796
797

        Examples
        --------
        >>> g = gt.Graph()
        >>> g.properties[("e", "foo")] = g.new_edge_property("vector<double>")
        >>> g.vertex_properties["foo"] = g.new_vertex_property("double")
        >>> g.vertex_properties["bar"] = g.new_vertex_property("python::object")
798
        >>> g.graph_properties["gnat"] = g.new_graph_property("string", "hi there!")
799
800
801
802
803
804
805
        >>> g.list_properties()
        gnat           (graph)   (type: string, val: hi there!)
        bar            (vertex)  (type: python::object)
        foo            (vertex)  (type: double)
        foo            (edge)    (type: vector<double>)
        """

806
807
808
809
        if len(self.__properties) == 0:
            return
        w = max([len(x[0]) for x in self.__properties.keys()]) + 4
        w = w if w > 14 else 14
810

Tiago Peixoto's avatar
Tiago Peixoto committed
811
        for k, v in self.__properties.iteritems():
812
813
814
            if k[0] == "g":
                print "%%-%ds (graph)   (type: %%s, val: %%s)" % w % \
                      (k[1], v.value_type(), str(v[self]))
Tiago Peixoto's avatar
Tiago Peixoto committed
815
        for k, v in self.__properties.iteritems():
816
817
818
            if k[0] == "v":
                print "%%-%ds (vertex)  (type: %%s)" % w % (k[1],
                                                            v.value_type())
Tiago Peixoto's avatar
Tiago Peixoto committed
819
        for k, v in self.__properties.iteritems():
820
821
822
823
824
825
826
            if k[0] == "e":
                print "%%-%ds (edge)    (type: %%s)" % w % (k[1],
                                                            v.value_type())

    # index properties

    def _get_vertex_index(self):
827
        return self.__vertex_index
828
829
    vertex_index = property(_get_vertex_index,
                            doc="Vertex index map. This map is immutable.")
830
831

    def _get_edge_index(self):
832
        return self.__edge_index
833
    edge_index = property(_get_edge_index, doc="Edge index map.")
834

835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
    def _get_max_edge_index(self):
        return self.__graph.GetMaxEdgeIndex()
    max_edge_index = property(_get_max_edge_index,
                              doc="The maximum value of the edge index map.")

    def reindex_edges(self):
        """
        Reset the edge indexes so that they lie in the [0, :meth:`~graph_tool.Graph.num_edges` - 1]
        range. The index ordering will be compatible with the sequence returned
        by the :meth:`~graph_tool.Graph.edges` function.

        .. WARNING::

           Calling this function will invalidate all existing edge property
           maps, if the index ordering is modified! The property maps will still
           be usable, but their contents will still be tied to the old indices,
           and thus may be scrambled.
        """
        self.__graph.ReIndexEdges()

855
856
    # Property map creation

Tiago Peixoto's avatar
Tiago Peixoto committed
857
    def new_property(self, key_type, value_type):
858
        """Create a new (uninitialized) vertex property map of key type
Tiago Peixoto's avatar
Tiago Peixoto committed
859
860
        ``key_type`` (``v``, ``e`` or ``g``), value type ``value_type``, and
        return it.
861
        """
862
        if key_type == "v" or key_type == "vertex":
Tiago Peixoto's avatar
Tiago Peixoto committed
863
            return self.new_vertex_property(value_type)
864
        if key_type == "e" or key_type == "edge":
Tiago Peixoto's avatar
Tiago Peixoto committed
865
            return self.new_edge_property(value_type)
866
        if key_type == "g" or key_type == "graph":
Tiago Peixoto's avatar
Tiago Peixoto committed
867
            return self.new_graph_property(value_type)
Tiago Peixoto's avatar
Tiago Peixoto committed
868
        raise ValueError("unknown key type: " + key_type)
869

Tiago Peixoto's avatar
Tiago Peixoto committed
870
871
872
873
    def new_vertex_property(self, value_type):
        """Create a new (uninitialized) vertex property map of type
        ``value_type``, and return it."""
        return PropertyMap(new_vertex_property(_type_alias(value_type),
874
875
                                               self.__graph.GetVertexIndex()),
                           self, "v")
876

Tiago Peixoto's avatar
Tiago Peixoto committed
877
878
879
880
    def new_edge_property(self, value_type):
        """Create a new (uninitialized) edge property map of type
        ``value_type``, and return it."""
        return PropertyMap(new_edge_property(_type_alias(value_type),
881
                                             self.__graph.GetEdgeIndex()),
882
883
                           self, "e")

Tiago Peixoto's avatar
Tiago Peixoto committed
884
885
886
887
    def new_graph_property(self, value_type, val=None):
        """Create a new graph property map of type ``value_type``, and return
        it. If ``val`` is not None, the property is initialized to its value."""
        prop = PropertyMap(new_graph_property(_type_alias(value_type),
888
889
                                              self.__graph.GetGraphIndex()),
                           self, "g", lambda k: k.__graph)
890
891
892
        if val != None:
            prop[self] = val
        return prop
893
894
895

    # property map copying
    @_require("src", PropertyMap)
896
    @_require("tgt", (PropertyMap, type(None)))
897
    def copy_property(self, src, tgt=None, value_type=None, g=None):
898
899
900
901
902
        """Copy contents of ``src`` property to ``tgt`` property. If ``tgt`` is
        None, then a new property map of the same type (or with the type given
        by the optional ``value_type`` parameter) is created, and returned. The
        optional parameter g specifies the (identical) source graph to copy
        properties from (defaults to self).
903
        """
904
        if tgt == None:
905
906
907
            tgt = self.new_property(src.key_type(),
                                    (src.value_type()
                                     if value_type == None else value_type))
908
909
910
911
            ret = tgt
        else:
            ret = None

912
        if src.key_type() != tgt.key_type():
Tiago Peixoto's avatar
Tiago Peixoto committed
913
            raise ValueError("source and target properties must have the same" +
914
915
916
917
918
919
920
                             " key type")
        if g == None:
            g = self
        if g != self:
            g.stash_filter()
        self.stash_filter()
        if src.key_type() == "v":
921
922
            self.__graph.CopyVertexProperty(g.__graph, _prop("v", g, src),
                                            _prop("v", g, tgt))
923
        elif src.key_type() == "e":
924
925
            self.__graph.CopyEdgeProperty(g.__graph, _prop("e", g, src),
                                            _prop("e", g, tgt))
926
927
928
929
930
        else:
            tgt[self] = src[g]
        self.pop_filter()
        if g != self:
            g.pop_filter()
931
        return ret
932

933
    # degree property map
Tiago Peixoto's avatar
Tiago Peixoto committed
934
    @_limit_args({"deg": ["in", "out", "total"]})
935
936
    def degree_property_map(self, deg):
        """Create and return a vertex property map containing the degree type
937
        given by ``deg``."""
938
939
        return PropertyMap(self.__graph.DegreeMap(deg), self, "v")

940
941
    # I/O operations
    # ==============
Tiago Peixoto's avatar
Tiago Peixoto committed
942
943
944
945
946
947
948
949
950
951
952
953
954
955
    def load(self, file_name, file_format="auto"):
        """Load graph from ``file_name`` (which can be either a string or a
        file-like object). The format is guessed from ``file_name``, or can be
        specified by ``file_format``, which can be either "xml" or "dot". """

        if type(file_name) == str:
            file_name = os.path.expanduser(file_name)
        if file_format == 'auto' and isinstance(file_name, str):
            if file_name.endswith(".xml") or file_name.endswith(".xml.gz") or \
                   file_name.endswith(".xml.bz2"):
                file_format = "xml"
            elif file_name.endswith(".dot") or file_name.endswith(".dot.gz") or \
                     file_name.endswith(".dot.bz2"):
                file_format = "dot"
956
            else:
Tiago Peixoto's avatar
Tiago Peixoto committed
957
958
959
960
961
                raise ValueError("cannot determine file format of: " + file_name)
        elif file_format == "auto":
            file_format = "xml"
        if isinstance(file_name, str):
            props = self.__graph.ReadFromFile(file_name, None, file_format)
962
        else:
963
            props = self.__graph.ReadFromFile("", file_name, file_format)
964
965
966
967
968
969
970
        for name, prop in props[0].iteritems():
            self.vertex_properties[name] = PropertyMap(prop, self, "v")
        for name, prop in props[1].iteritems():
            self.edge_properties[name] = PropertyMap(prop, self, "e")
        for name, prop in props[2].iteritems():
            self.graph_properties[name] = PropertyMap(prop, self, "g",
                                                      lambda k: k.__graph)
971

Tiago Peixoto's avatar
Tiago Peixoto committed
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    def save(self, file_name, file_format="auto"):
        """Save graph to ``file_name`` (which can be either a string or a
        file-like object). The format is guessed from the ``file_name``, or can
        be specified by ``file_format``, which can be either "xml" or "dot". """

        if type(file_name) == str:
            file_name = os.path.expanduser(file_name)
        if file_format == 'auto' and isinstance(file_name, str):
            if file_name.endswith(".xml") or file_name.endswith(".xml.gz") or \
                   file_name.endswith(".xml.bz2"):
                file_format = "xml"
            elif file_name.endswith(".dot") or file_name.endswith(".dot.gz") or \
                     file_name.endswith(".dot.bz2"):
                file_format = "dot"
986
            else:
Tiago Peixoto's avatar
Tiago Peixoto committed
987
988
989
990
                raise ValueError("cannot determine file file_format of: " + file_name)
        elif file_format == "auto":
            file_format = "xml"
        props = [(name[1], prop._PropertyMap__map) for name, prop in \
991
                 self.__properties.iteritems()]
Tiago Peixoto's avatar
Tiago Peixoto committed
992
993
        if isinstance(file_name, str):
            self.__graph.WriteToFile(file_name, None, file_format, props)
994
        else:
Tiago Peixoto's avatar
Tiago Peixoto committed
995
            self.__graph.WriteToFile("", file_name, file_format, props)
996

997
998
    # Directedness
    # ============
999
1000

    def set_directed(self, is_directed):
1001
        """Set the directedness of the graph."""
1002
1003
1004
        self.__graph.SetDirected(is_directed)

    def is_directed(self):
1005
        """Get the directedness of the graph."""
1006
1007
        return self.__graph.GetDirected()

1008
1009
1010
    # Reversedness
    # ============

1011
    def set_reversed(self, is_reversed):
1012
1013
        """Reverse the direction of the edges, if ``is_reversed`` is ``True``,
        or maintain the original direction otherwise."""
1014
1015
1016
        self.__graph.SetReversed(is_reversed)

    def is_reversed(self):
1017
1018
        """Return ``True`` if the edges are reversed, and ``False`` otherwise.
        """
1019
1020
        return self.__graph.GetReversed()

1021
1022
1023
    # Filtering
    # =========

Tiago Peixoto's avatar
Tiago Peixoto committed
1024
    def set_vertex_filter(self, prop, inverted=False):
1025
        """Choose vertex boolean filter property. Only the vertices with value
1026
1027
1028
1029
1030
        different than zero are kept in the filtered graph. If the ``inverted``
        option is supplied with value ``True``, only the vertices with value
        zero are kept. If the supplied property is ``None``, any previous
        filtering is removed."""

Tiago Peixoto's avatar
Tiago Peixoto committed
1031
        self.__graph.SetVertexFilterProperty(_prop("v", self, prop),
1032
                                             inverted)
Tiago Peixoto's avatar
Tiago Peixoto committed
1033
        self.__filter_state["vertex_filter"] = (prop, inverted)
1034
1035

    def get_vertex_filter(self):
1036
1037
        """Return a tuple with the vertex filter property and bool value
        indicating whether or not it is inverted."""
1038
        return self.__filter_state["vertex_filter"]
1039

Tiago Peixoto's avatar
Tiago Peixoto committed
1040
    def set_edge_filter(self, prop, inverted=False):
1041
        """Choose edge boolean filter property. Only the edges with value
1042
1043
1044
1045
        different than zero are kept in the filtered graph. If the ``inverted``
        option is supplied with value ``True``, only the edges with value zero
        are kept. If the supplied property is ``None``, any previous filtering
        is removed."""
Tiago Peixoto's avatar
Tiago Peixoto committed
1046
1047
        self.__graph.SetEdgeFilterProperty(_prop("e", self, prop), inverted)
        self.__filter_state["edge_filter"] = (prop, inverted)
1048

1049
    def get_edge_filter(self):
1050
1051
        """Return a tuple with the edge filter property and bool value
        indicating whether or not it is inverted."""
1052
        return self.__filter_state["edge_filter"]
1053
1054
1055

    def purge_vertices(self):
        """Remove all vertices of the graph which are currently being filtered
1056
        out, and return it to the unfiltered state."""
1057
        self.__graph.PurgeVertices()
1058
        self.set_vertex_filter(None)
1059
1060
1061

    def purge_edges(self):
        """Remove all edges of the graph which are currently being filtered out,
1062
        and return it to the unfiltered state."""
1063
        self.__graph.PurgeEdges()
1064
        self.set_edge_filter(None)
1065

1066
1067
1068
1069
1070
    def stash_filter(self, edge=False, vertex=False, directed=False,
                     reversed=False, all=True):
        """Stash current filter state and set the graph to its unfiltered
        state. The optional keyword arguments specify which type of filter
        should be stashed."""
1071
1072
        if edge or vertex or directed or reversed:
            all = False
Tiago Peixoto's avatar
Tiago Peixoto committed
1073
        self.__stashed_filter_state.append(self.get_filter_state())
1074
        if libcore.graph_filtering_enabled():
1075
1076
1077
1078
1079
1080
1081
1082
1083
            if vertex or all:
                self.set_vertex_filter(None)
            if edge or all:
                self.set_edge_filter(None)
        if directed or all:
            self.set_directed(True)
        if reversed or all:
            self.set_reversed(False)

Tiago Peixoto's avatar
Tiago Peixoto committed
1084
1085
    def pop_filter(self, edge=False, vertex=False, directed=False,
                   reversed=False, all=True):
1086
1087
        """Pop last stashed filter state. The optional keyword arguments specify
        which type of filter should be recovered."""
1088
1089
        if edge or vertex or directed or reversed:
            all = False
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
        state = self.__stashed_filter_state.pop()
        if libcore.graph_filtering_enabled():
            if vertex or all:
                self.set_vertex_filter(state["vertex_filter"][0],
                                       state["vertex_filter"][1])
            if edge or all:
                self.set_edge_filter(state["edge_filter"][0],
                                     state["edge_filter"][1])
        if directed or all:
            self.set_directed(state["directed"])
        if reversed or all:
            self.set_reversed(state["reversed"])
1102

1103
1104
    def get_filter_state(self):
        """Return a copy of the filter state of the graph."""
Tiago Peixoto's avatar
Tiago Peixoto committed
1105
1106
        self.__filter_state["directed"] = self.is_directed()
        self.__filter_state["reversed"] = self.is_reversed()
1107
1108
1109
1110
        return copy.copy(self.__filter_state)

    def set_filter_state(self, state):
        """Set the filter state of the graph."""
1111
1112
1113
1114
1115
        if libcore.graph_filtering_enabled():
            self.set_vertex_filter(state["vertex_filter"][0],
                                   state["vertex_filter"][1])
            self.set_edge_filter(state["edge_filter"][0],
                                 state["edge_filter"][1])
1116
1117
1118
        self.set_directed(state["directed"])
        self.set_reversed(state["reversed"])