core.py 49.4 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
    alias = {"int8_t": "bool",
             "boolean": "bool",
             "int": "int32_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
83
             "long": "int64_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
84
             "long long": "int64_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
85
86
             "object": "python::object",
             "float": "double"}
87
88
    if type_name in value_types():
        return type_name
Tiago Peixoto's avatar
Tiago Peixoto committed
89
    if type_name in alias:
90
        return alias[type_name]
91
    ma = re.compile(r"vector<(.*)>").match(type_name)
92
93
    if ma:
        t = ma.group(1)
Tiago Peixoto's avatar
Tiago Peixoto committed
94
        if t in alias:
95
96
97
            return "vector<%s>" % alias[t]
    raise ValueError("invalid property value type: " + type_name)

Tiago Peixoto's avatar
Tiago Peixoto committed
98

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def _python_type(type_name):
    type_name = _type_alias(type_name)
    if "vector" in type_name:
        ma = re.compile(r"vector<(.*)>").match(type_name)
        t = ma.group(1)
        return list, _python_type(t)
    if "int" in type_name:
        return int
    if type_name == "bool":
        return bool
    if "double" in type_name:
        return float
    if "string" in type_name:
        return str
    return object


Tiago Peixoto's avatar
Tiago Peixoto committed
116
def show_config():
117
    """Show ``graph_tool`` build configuration."""
Tiago Peixoto's avatar
Tiago Peixoto committed
118
119
120
121
122
123
124
125
126
    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())
127

128
################################################################################
129
# Property Maps
130
131
################################################################################

Tiago Peixoto's avatar
Tiago Peixoto committed
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
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
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
    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
233
234
235
236
237
238
    arbitrary properties.

    The possible property types are listed below.

    .. table::

Tiago Peixoto's avatar
Tiago Peixoto committed
239
        =======================     ======================
Tiago Peixoto's avatar
Tiago Peixoto committed
240
         Type name                  Alias
Tiago Peixoto's avatar
Tiago Peixoto committed
241
        =======================     ======================
Tiago Peixoto's avatar
Tiago Peixoto committed
242
        ``bool``                    ``uint8_t``
243
        ``int32_t``                 ``int``
Tiago Peixoto's avatar
Tiago Peixoto committed
244
        ``int64_t``                 ``long``, ``long long``
Tiago Peixoto's avatar
Tiago Peixoto committed
245
        ``double``                  ``float``
246
247
        ``long double``
        ``string``
Tiago Peixoto's avatar
Tiago Peixoto committed
248
249
        ``vector<bool>``            ``vector<uint8_t>``
        ``vector<int32_t>``         ``vector<int>``
Tiago Peixoto's avatar
Tiago Peixoto committed
250
        ``vector<int64_t>``         ``vector<long>``, ``vector<long long>``
Tiago Peixoto's avatar
Tiago Peixoto committed
251
252
253
        ``vector<double>``          ``vector<float>``
        ``vector<long double>``
        ``vector<string>``
254
        ``python::object``          ``object``
Tiago Peixoto's avatar
Tiago Peixoto committed
255
        =======================     ======================
Tiago Peixoto's avatar
Tiago Peixoto committed
256
    """
Tiago Peixoto's avatar
Tiago Peixoto committed
257
    def __init__(self, pmap, g, key_type, key_trans=None):
258
        self.__map = pmap
259
        self.__g = weakref.ref(g)
260
        self.__key_type = key_type
261
        self.__key_trans = key_trans if key_trans is not None else lambda k: k
262
263
264
        self.__register_map()

    def __register_map(self):
265
266
267
268
        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
269

270
    def __unregister_map(self):
271
272
273
274
275
        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]
276
277
278
279
280
281
282
283

    def __del__(self):
        self.__unregister_map()

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

    def __setitem__(self, k, v):
284
285
286
287
288
289
290
291
292
293
294
        try:
            self.__map[self.__key_trans(k)] = v
        except TypeError:
            # attempt to convert to a compatible python type. This is useful,
            # for instance, when dealing with numpy scalar types.
            valtype = self.python_value_type()
            if isistance(valtype, tuple):
                val = [valtype[1](x) for x in v]
            else:
                val = valtype(v)
            self.__map[self.__key_trans(k)] = val
295

296
297
298
299
    def __repr__(self):
        # provide some more useful information
        if self.key_type() == "e":
            k = "Edge"
Tiago Peixoto's avatar
Tiago Peixoto committed
300
        elif self.key_type() == "v":
301
302
303
304
305
306
307
308
309
310
311
            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))

312
    def get_graph(self):
313
        """Get the graph class to which the map refers."""
314
        return self.__g()
315
316

    def key_type(self):
317
        """Return the key type of the map. Either 'g', 'v' or 'e'."""
318
319
320
        return self.__key_type

    def value_type(self):
321
        """Return the value type of the map."""
322
323
        return self.__map.value_type()

324
325
326
327
    def python_value_type(self):
        """Return the python-compatible value type of the map."""
        return _python_type(self.__map.value_type())

328
    def get_array(self):
329
        """Get a :class:`~graph_tool.PropertyArray` with the property values.
330
331
332
333

        .. WARNING::

           The returned array does not own the data, which belongs to the
334
335
336
337
           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.
338
        """
339
        a = self._get_data()
340
341
        if a is None:
            return None
342
343
344
345
346
        return PropertyArray(a, prop_map=self)

    def _get_data(self):
        if self.__g() is None:
            return None
347
        self.__g().stash_filter(edge=True, vertex=True)
348
349
350
        if self.__key_type == 'v':
            n = self.__g().num_vertices()
        elif self.__key_type == 'e':
351
            n = self.__g()._Graph__graph.GetMaxEdgeIndex() + 1
352
353
        else:
            n = 1
354
        self.__g().pop_filter(edge=True, vertex=True)
355
356
        a = self.__map.get_array(n)
        return a
357

Tiago Peixoto's avatar
Tiago Peixoto committed
358
    def __get_array(self):
359
        if self.get_array() is not None:
360
361
362
            return self.get_array()[:]
        else:
            return None
Tiago Peixoto's avatar
Tiago Peixoto committed
363
364
365
366
367
368
369

    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
370
                 array itself, for convenience.""")
Tiago Peixoto's avatar
Tiago Peixoto committed
371

372
373
374
375
    def is_writable(self):
        """Return True if the property is writable."""
        return self.__map.is_writable()

Tiago Peixoto's avatar
Tiago Peixoto committed
376

377
378
379
380
381
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
382

383
384
385
386
387
388
389
390
391
392
393
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
394

395
def _check_prop_vector(prop, name=None, scalar=True, floating=False):
396
397
    scalars = ["bool", "int32_t", "int64_t", "unsigned long",
               "double", "long double"]
398
399
    if not scalar:
        scalars += ["string"]
400
401
402
403
404
405
406
407
    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
408

Tiago Peixoto's avatar
Tiago Peixoto committed
409
def group_vector_property(props, value_type=None, vprop=None, pos=None):
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    """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``.
    """
431
    g = props[0].get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
432
    vtypes = set()
433
    keys = set()
Tiago Peixoto's avatar
Tiago Peixoto committed
434
    for i, p in enumerate(props):
435
436
437
        if "vector" in p.value_type():
            raise ValueError("property map 'props[%d]' is a vector property." %
                             i)
Tiago Peixoto's avatar
Tiago Peixoto committed
438
        vtypes.add(p.value_type())
439
440
        keys.add(p.key_type())
    if len(keys) > 1:
Tiago Peixoto's avatar
Tiago Peixoto committed
441
        raise ValueError("'props' must be of the same key type.")
442
443
444
    k = keys.pop()

    if vprop == None:
Tiago Peixoto's avatar
Tiago Peixoto committed
445
446
        if value_type == None and len(vtypes) == 1:
            value_type = vtypes.pop()
447
448
449
450
451
452
453
454
455
456
457
458

        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.")
459
    _check_prop_vector(vprop, name="vprop", scalar=False)
460

Tiago Peixoto's avatar
Tiago Peixoto committed
461
    for i, p in enumerate(props):
462
463
464
465
466
467
468
469
470
471
472
473
474
475
        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
476

477
def ungroup_vector_property(vprop, pos, props=None):
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    """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``.
    """

498
    g = vprop.get_graph()
499
    _check_prop_vector(vprop, name="vprop", scalar=False)
500
501
502
503
504
505
506
507
508
509
    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
510
    for i, p in enumerate(pos):
511
512
513
514
515
516
517
518
519
520
        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
521
                                            p, k == 'e')
522
523
524
            g.pop_filter(directed=True, reversed=True)
        else:
            if len(vprop[g]) <= pos[i]:
Tiago Peixoto's avatar
Tiago Peixoto committed
525
                vprop[g].resize(pos[i] + 1)
526
527
            props[i][g] = vprop[g][pos[i]]
    return props
528

Tiago Peixoto's avatar
Tiago Peixoto committed
529

530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
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)
551
552
553
554
555
556

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

Tiago Peixoto's avatar
Tiago Peixoto committed
557
558
559
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
560

Tiago Peixoto's avatar
Tiago Peixoto committed
561

562
class Graph(object):
Tiago Peixoto's avatar
Tiago Peixoto committed
563
564
565
    """Generic multigraph class.

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

Tiago Peixoto's avatar
Tiago Peixoto committed
569
570
571
572
573
574
575
576
    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

577
    """
578

Tiago Peixoto's avatar
Tiago Peixoto committed
579
    def __init__(self, g=None, directed=True):
580
581
        """Construct a graph. If ``g`` is specified, the graph (and its internal
        properties) will be copied. The ``directed`` parameter specifies whether
582
        the graph should be directed or undirected."""
583
584
585
        self.__properties = {}
        self.__known_properties = []
        self.__filter_state = {"reversed": False,
Tiago Peixoto's avatar
Tiago Peixoto committed
586
587
588
                               "edge_filter": (None, False),
                               "vertex_filter": (None, False),
                               "directed": True}
589
590
        self.__stashed_filter_state = []

591
        if g == None:
592
            self.__graph = libcore.GraphInterface()
593
            self.set_directed(directed)
594
        else:
595
            self.__graph = libcore.GraphInterface(g.__graph)
Tiago Peixoto's avatar
Tiago Peixoto committed
596
            for k, v in g.__properties.iteritems():
597
598
                new_p = self.new_property(v.key_type(), v.value_type())
                self.copy_property(v, new_p, g)
599
                self.properties[k] = new_p
Tiago Peixoto's avatar
Tiago Peixoto committed
600
601
602

            self.__stashed_filter_state = [self.get_filter_state()]

603
604
605
606
607
608
609
            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
610
                    for k, v in g.vertex_properties.iteritems():
611
612
613
614
615
616
617
618
619
620
621
                        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
622
                    for k, v in g.edge_properties.iteritems():
623
624
625
626
627
                        if v == e_filt:
                            new_filt = self.edge_properties[k]
                self.__stashed_filter_state[0]["edge_filter"] = (new_filt,
                                                                 e_rev)
            self.pop_filter()
628
629
630
631
632
        # 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")
633

634
635
636
637
        # modification permissions
        self.__perms = {"add_edge": True, "del_edge": True,
                        "add_vertex": True, "del_vertex": True}

638
    def copy(self):
639
        """Return a deep copy of self. All internal property maps are also
640
641
        copied."""
        return Graph(self)
642

643
644
645
646
647
648
649
650
651
652
653
    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()
654
        return "<Graph object, %s%s, with %d %s and %d edge%s%s at 0x%x>"\
655
656
657
               % (d, fr, n, "vertex" if n == 1 else "vertices", e,
                  "" if e == 1 else "s", f, id(self))

658
    # Graph access
659
    # ============
660

661
662
663
664
    def __check_perms(self, ptype):
        if not self.__perms[ptype]:
            raise RuntimeError("the graph cannot be modified at this point!")

665
    def vertices(self):
666
        """Return an iterator over the vertices.
667
668
669
670
671
672
673
674
675
676
677
678

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

        """
679
        return libcore.get_vertices(weakref.ref(self.__graph))
680

681
682
683
684
    def vertex(self, i, use_index=True):
        """Return the vertex with index ``i``. If ``use_index=False``, the
        ``i``-th vertex is returned (which can differ from the vertex with index
        ``i`` in case of filtered graphs). """
685
686
687
        if use_index:
            self.stash_filter(vertex=True)
        try:
Tiago Peixoto's avatar
Tiago Peixoto committed
688
            v = libcore.get_vertex(weakref.ref(self.__graph), int(i))
689
690
691
692
        finally:
            if use_index:
                self.pop_filter(vertex=True)
        return v
693
694

    def edges(self):
695
        """Return an iterator over the edges."""
696
        return libcore.get_edges(weakref.ref(self.__graph))
697

698
    def add_vertex(self, n=1):
699
700
        """Add a vertex to the graph, and return it. If ``n > 1``, ``n``
        vertices are inserted and a list is returned."""
701
        self.__check_perms("add_vertex")
702
        vlist = [libcore.add_vertex(weakref.ref(self.__graph)) \
Tiago Peixoto's avatar
Tiago Peixoto committed
703
                 for i in xrange(0, n)]
704
        if n == 1:
705
706
            return vlist[0]
        return vlist
707

708
    def remove_vertex(self, vertex):
709
        """Remove a vertex from the graph."""
710
        self.__check_perms("del_vertex")
711
712
        index = self.vertex_index[vertex]
        for pmap in self.__known_properties:
713
714
715
            if pmap[0] == "v" and pmap[1]() != None and \
                   pmap[1]() != self.__vertex_index._PropertyMap__map:
                self.__graph.ShiftVertexProperty(pmap[1]().get_map(), index)
716
        self.clear_vertex(vertex)
717
        libcore.remove_vertex(self.__graph, vertex)
718

719
    def remove_vertex_if(self, predicate):
720
721
        """Remove all the vertices from the graph for which ``predicate(v)``
        evaluates to ``True``. """
722
723
724
725
726
727
        N = self.num_vertices()
        for i in xrange(0, N):
            v = self.vertex(N - i - 1)
            if predicate(v):
                self.remove_vertex(v)

728
    def clear_vertex(self, vertex):
729
        """Remove all in and out-edges from the given vertex."""
730
        del_es = set()
731
        for e in vertex.all_edges():
732
            del_es.add(e)
733
734
735
        for e in del_es:
            self.remove_edge(e)

736
    def add_edge(self, source, target):
737
        """Add a new edge from ``source`` to ``target`` to the graph, and return
738
        it."""
739
        self.__check_perms("add_edge")
740
        return libcore.add_edge(weakref.ref(self.__graph), source, target)
741

742
    def remove_edge(self, edge):
743
        """Remove an edge from the graph."""
744
        self.__check_perms("del_edge")
745
        return libcore.remove_edge(self.__graph, edge)
746

747
    def remove_edge_if(self, predicate):
748
749
        """Remove all edges from the graph, for which ``predicate(e)`` evaluates
        to ``True``."""
750
751
752
753
754
755
756
757
        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)

758
    def clear(self):
759
        """Remove all vertices and edges from the graph."""
760
761
        self.__check_perms("del_vertex")
        self.__check_perms("del_edge")
762
763
        self.__graph.Clear()

764
    def clear_edges(self):
765
        """Remove all edges from the graph."""
766
        self.__check_perms("del_edge")
767
768
769
770
771
772
773
774
        self.__graph.ClearEdges()

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

    # all properties
    def __get_properties(self):
        return PropertyDict(self, self.__properties,
Tiago Peixoto's avatar
Tiago Peixoto committed
775
776
777
                            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]))
778

Tiago Peixoto's avatar
Tiago Peixoto committed
779
    @_limit_args({"t": ["v", "e", "g"]})
780
781
782
783
784
    @_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
785
        self.__properties[(t, k)] = v
786

Tiago Peixoto's avatar
Tiago Peixoto committed
787
    @_limit_args({"t": ["v", "e", "g"]})
788
789
    @_require("k", str)
    def __del_property(self, t, k):
Tiago Peixoto's avatar
Tiago Peixoto committed
790
        del self.__properties[(t, k)]
791
792

    properties = property(__get_properties,
793
794
795
796
797
798
799
800
801
802
803
804
                          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")]
    """)
805
806

    def __get_specific_properties(self, t):
Tiago Peixoto's avatar
Tiago Peixoto committed
807
        props = dict([(k[1], v) for k,v in self.__properties.iteritems() \
808
809
810
811
                      if k[0] == t ])
        return props

    # vertex properties
812
    def __get_vertex_properties(self):
813
        return PropertyDict(self, self.__get_specific_properties("v"),
Tiago Peixoto's avatar
Tiago Peixoto committed
814
815
816
                            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))
817
818
    vertex_properties = property(__get_vertex_properties,
                                 doc="Dictionary of vertex properties")
Tiago Peixoto's avatar
Tiago Peixoto committed
819

820
    # edge properties
821
    def __get_edge_properties(self):
822
        return PropertyDict(self, self.__get_specific_properties("e"),
Tiago Peixoto's avatar
Tiago Peixoto committed
823
824
825
                            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))
826
827
828
    edge_properties = property(__get_edge_properties,
                                 doc="Dictionary of edge properties")

829
    # graph properties
830
    def __get_graph_properties(self):
831
        return PropertyDict(self, self.__get_specific_properties("g"),
Tiago Peixoto's avatar
Tiago Peixoto committed
832
833
834
                            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))
835
836
837
838
    graph_properties = property(__get_graph_properties,
                                 doc="Dictionary of graph properties")

    def list_properties(self):
839
        """List all internal properties.
840
841
842
843
844
845
846

        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")
847
        >>> g.graph_properties["gnat"] = g.new_graph_property("string", "hi there!")
848
849
850
851
852
853
854
        >>> g.list_properties()
        gnat           (graph)   (type: string, val: hi there!)
        bar            (vertex)  (type: python::object)
        foo            (vertex)  (type: double)
        foo            (edge)    (type: vector<double>)
        """

855
856
857
858
        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
859

Tiago Peixoto's avatar
Tiago Peixoto committed
860
        for k, v in self.__properties.iteritems():
861
862
863
            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
864
        for k, v in self.__properties.iteritems():
865
866
867
            if k[0] == "v":
                print "%%-%ds (vertex)  (type: %%s)" % w % (k[1],
                                                            v.value_type())
Tiago Peixoto's avatar
Tiago Peixoto committed
868
        for k, v in self.__properties.iteritems():
869
870
871
872
873
874
875
            if k[0] == "e":
                print "%%-%ds (edge)    (type: %%s)" % w % (k[1],
                                                            v.value_type())

    # index properties

    def _get_vertex_index(self):
876
        return self.__vertex_index
877
878
    vertex_index = property(_get_vertex_index,
                            doc="Vertex index map. This map is immutable.")
879
880

    def _get_edge_index(self):
881
        return self.__edge_index
882
    edge_index = property(_get_edge_index, doc="Edge index map.")
883

884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
    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()

904
905
    # Property map creation

Tiago Peixoto's avatar
Tiago Peixoto committed
906
    def new_property(self, key_type, value_type):
907
        """Create a new (uninitialized) vertex property map of key type
Tiago Peixoto's avatar
Tiago Peixoto committed
908
909
        ``key_type`` (``v``, ``e`` or ``g``), value type ``value_type``, and
        return it.
910
        """
911
        if key_type == "v" or key_type == "vertex":
Tiago Peixoto's avatar
Tiago Peixoto committed
912
            return self.new_vertex_property(value_type)
913
        if key_type == "e" or key_type == "edge":
Tiago Peixoto's avatar
Tiago Peixoto committed
914
            return self.new_edge_property(value_type)
915
        if key_type == "g" or key_type == "graph":
Tiago Peixoto's avatar
Tiago Peixoto committed
916
            return self.new_graph_property(value_type)
Tiago Peixoto's avatar
Tiago Peixoto committed
917
        raise ValueError("unknown key type: " + key_type)
918

Tiago Peixoto's avatar
Tiago Peixoto committed
919
920
921
922
    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),
923
924
                                               self.__graph.GetVertexIndex()),
                           self, "v")
925

Tiago Peixoto's avatar
Tiago Peixoto committed
926
927
928
929
    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),
930
                                             self.__graph.GetEdgeIndex()),
931
932
                           self, "e")

Tiago Peixoto's avatar
Tiago Peixoto committed
933
934
935
936
    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),
937
938
                                              self.__graph.GetGraphIndex()),
                           self, "g", lambda k: k.__graph)
939
940
941
        if val != None:
            prop[self] = val
        return prop
942
943
944

    # property map copying
    @_require("src", PropertyMap)
945
    @_require("tgt", (PropertyMap, type(None)))
946
    def copy_property(self, src, tgt=None, value_type=None, g=None):
947
948
949
950
951
        """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).
952
        """
953
        if tgt == None:
954
955
956
            tgt = self.new_property(src.key_type(),
                                    (src.value_type()
                                     if value_type == None else value_type))
957
958
959
960
            ret = tgt
        else:
            ret = None

961
        if src.key_type() != tgt.key_type():
Tiago Peixoto's avatar
Tiago Peixoto committed
962
            raise ValueError("source and target properties must have the same" +
963
964
965
966
967
968
969
                             " key type")
        if g == None:
            g = self
        if g != self:
            g.stash_filter()
        self.stash_filter()
        if src.key_type() == "v":
970
971
            self.__graph.CopyVertexProperty(g.__graph, _prop("v", g, src),
                                            _prop("v", g, tgt))
972
        elif src.key_type() == "e":
973
974
            self.__graph.CopyEdgeProperty(g.__graph, _prop("e", g, src),
                                            _prop("e", g, tgt))
975
976
977
978
979
        else:
            tgt[self] = src[g]
        self.pop_filter()
        if g != self:
            g.pop_filter()
980
        return ret
981

982
    # degree property map
Tiago Peixoto's avatar
Tiago Peixoto committed
983
    @_limit_args({"deg": ["in", "out", "total"]})
984
985
    def degree_property_map(self, deg):
        """Create and return a vertex property map containing the degree type
986
        given by ``deg``."""
987
988
        return PropertyMap(self.__graph.DegreeMap(deg), self, "v")

989
990
    # I/O operations
    # ==============
Tiago Peixoto's avatar
Tiago Peixoto committed
991
992
993
994
995
996
997
998
999
1000
    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"):
For faster browsing, not all history is shown. View entire blame