core.py 41.9 KB
Newer Older
1
#! /usr/bin/env python
2
3
# -*- coding: utf-8 -*-
#
4
# graph_tool -- a general graph manipulation python module
5
#
6
# Copyright (C) 2007-2010 Tiago de Paula Peixoto <tiago@forked.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
36
37
38

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

Tiago Peixoto's avatar
Tiago Peixoto committed
39

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

Tiago Peixoto's avatar
Tiago Peixoto committed
61

62
63
def _degree(g, name):
    """Retrieve the degree type from string, or returns the corresponding
64
    property map."""
65
66
67
68
69
70
71
72
73
74
    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
75

Tiago Peixoto's avatar
Tiago Peixoto committed
76

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

Tiago Peixoto's avatar
Tiago Peixoto committed
95

Tiago Peixoto's avatar
Tiago Peixoto committed
96
def show_config():
97
    """Show ``graph_tool`` build configuration."""
Tiago Peixoto's avatar
Tiago Peixoto committed
98
99
100
101
102
103
104
105
106
    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())
107

108
################################################################################
109
# Property Maps
110
111
################################################################################

Tiago Peixoto's avatar
Tiago Peixoto committed
112

113
class PropertyMap(object):
114
    """Property map class."""
Tiago Peixoto's avatar
Tiago Peixoto committed
115
    def __init__(self, pmap, g, key_type, key_trans=None):
116
        self.__map = pmap
117
        self.__g = weakref.ref(g)
118
119
120
121
122
        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):
123
124
125
126
        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
127

128
    def __unregister_map(self):
129
130
131
132
133
        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]
134
135
136
137
138
139
140
141
142
143

    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

144
145
146
147
    def __repr__(self):
        # provide some more useful information
        if self.key_type() == "e":
            k = "Edge"
Tiago Peixoto's avatar
Tiago Peixoto committed
148
        elif self.key_type() == "v":
149
150
151
152
153
154
155
156
157
158
159
            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))

160
    def get_graph(self):
161
        """Get the graph class to which the map refers."""
162
        return self.__g()
163
164

    def key_type(self):
165
        """Return the key type of the map. Either 'g', 'v' or 'e'."""
166
167
168
        return self.__key_type

    def value_type(self):
169
        """Return the value type of the map."""
170
171
        return self.__map.value_type()

172
    def get_array(self):
Tiago Peixoto's avatar
Tiago Peixoto committed
173
        """Get an array with property values.
174
175
176
177
178

        .. WARNING::

           The returned array does not own the data, which belongs to the
           property map. Therefore, the returned array cannot have a longer
Tiago Peixoto's avatar
Tiago Peixoto committed
179
           lifespan than the property map itself! Furthermore, if the graph
180
181
182
183
           changes, it may leave the pointer to the data in the array dangling!
           Do *not* store the array if the graph is to be modified, or the
           original property map deleted; *store a copy instead*!
        """
184
        self.__g().stash_filter(edge=True, vertex=True)
185
186
187
188
189
190
        if self.__key_type == 'v':
            n = self.__g().num_vertices()
        elif self.__key_type == 'e':
            n = self.__g().num_edges()
        else:
            n = 1
191
        self.__g().pop_filter(edge=True, vertex=True)
192
193
        return self.__map.get_array(n)

Tiago Peixoto's avatar
Tiago Peixoto committed
194
    def __get_array(self):
195
196
197
198
        if self.get_array() != None:
            return self.get_array()[:]
        else:
            return None
Tiago Peixoto's avatar
Tiago Peixoto committed
199
200
201
202
203
204
205
206
207

    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
                 array, for convenience.""")

208
209
210
211
    def is_writable(self):
        """Return True if the property is writable."""
        return self.__map.is_writable()

Tiago Peixoto's avatar
Tiago Peixoto committed
212

213
214
215
216
217
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
218

219
220
221
222
223
224
225
226
227
228
229
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
230

231
def _check_prop_vector(prop, name=None, scalar=True, floating=False):
232
233
    scalars = ["bool", "int32_t", "int64_t", "unsigned long",
               "double", "long double"]
234
235
    if not scalar:
        scalars += ["string"]
236
237
238
239
240
241
242
243
    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
244

245
def group_vector_property(g, props, value_type=None, vprop=None, pos=None):
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    """Group list of properties ``props`` into a vector property map of the same
    type.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to which the property maps belong.
    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``.
    """
Tiago Peixoto's avatar
Tiago Peixoto committed
269
    vtypes = set()
270
    keys = set()
Tiago Peixoto's avatar
Tiago Peixoto committed
271
    for i, p in enumerate(props):
272
273
274
        if "vector" in p.value_type():
            raise ValueError("property map 'props[%d]' is a vector property." %
                             i)
Tiago Peixoto's avatar
Tiago Peixoto committed
275
        vtypes.add(p.value_type())
276
277
        keys.add(p.key_type())
    if len(keys) > 1:
Tiago Peixoto's avatar
Tiago Peixoto committed
278
        raise ValueError("'props' must be of the same key type.")
279
280
281
    k = keys.pop()

    if vprop == None:
Tiago Peixoto's avatar
Tiago Peixoto committed
282
283
        if value_type == None and len(vtypes) == 1:
            value_type = vtypes.pop()
284
285
286
287
288
289
290
291
292
293
294
295

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

Tiago Peixoto's avatar
Tiago Peixoto committed
298
    for i, p in enumerate(props):
299
300
301
302
303
304
305
306
307
308
309
310
311
312
        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
313

314
def ungroup_vector_property(g, vprop, pos, props=None):
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    """Ungroup vector property map ``vprop`` into a list of individual property
    maps.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to which the property map belong.
    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``.
    """

337
    _check_prop_vector(vprop, name="vprop", scalar=False)
338
339
340
341
342
343
344
345
346
347
    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
348
    for i, p in enumerate(pos):
349
350
351
352
353
354
355
356
357
358
        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
359
                                            p, k == 'e')
360
361
362
            g.pop_filter(directed=True, reversed=True)
        else:
            if len(vprop[g]) <= pos[i]:
Tiago Peixoto's avatar
Tiago Peixoto committed
363
                vprop[g].resize(pos[i] + 1)
364
365
            props[i][g] = vprop[g][pos[i]]
    return props
366

Tiago Peixoto's avatar
Tiago Peixoto committed
367

368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
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)
389
390
391
392
393
394

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

Tiago Peixoto's avatar
Tiago Peixoto committed
395
396
397
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
398

Tiago Peixoto's avatar
Tiago Peixoto committed
399

400
class Graph(object):
401
402
403
    """This class encapsulates either a directed multigraph (default or if
    ``directed=True``) or an undirected multigraph (if ``directed=False``), with
    optional internal edge, vertex or graph properties.
404

405
    It is implemented as an adjacency list, where both vertex and edge lists are
Tiago Peixoto's avatar
Tiago Peixoto committed
406
    C++ STL vectors.
407
    """
408

Tiago Peixoto's avatar
Tiago Peixoto committed
409
    def __init__(self, g=None, directed=True):
410
411
        """Construct a graph. If ``g`` is specified, the graph (and its internal
        properties) will be copied. The ``directed`` parameter specifies whether
412
        the graph should be directed or undirected."""
413
414
415
        self.__properties = {}
        self.__known_properties = []
        self.__filter_state = {"reversed": False,
Tiago Peixoto's avatar
Tiago Peixoto committed
416
417
418
                               "edge_filter": (None, False),
                               "vertex_filter": (None, False),
                               "directed": True}
419
420
        self.__stashed_filter_state = []

421
        if g == None:
422
            self.__graph = libcore.GraphInterface()
423
            self.set_directed(directed)
424
        else:
425
            self.__graph = libcore.GraphInterface(g.__graph)
Tiago Peixoto's avatar
Tiago Peixoto committed
426
            for k, v in g.__properties.iteritems():
427
428
                new_p = self.new_property(v.key_type(), v.value_type())
                self.copy_property(v, new_p, g)
429
                self.properties[k] = new_p
Tiago Peixoto's avatar
Tiago Peixoto committed
430
431
432

            self.__stashed_filter_state = [self.get_filter_state()]

433
434
435
436
437
438
439
            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
440
                    for k, v in g.vertex_properties.iteritems():
441
442
443
444
445
446
447
448
449
450
451
                        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
452
                    for k, v in g.edge_properties.iteritems():
453
454
455
456
457
                        if v == e_filt:
                            new_filt = self.edge_properties[k]
                self.__stashed_filter_state[0]["edge_filter"] = (new_filt,
                                                                 e_rev)
            self.pop_filter()
458
459
460
461
462
        # 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")
463
464

    def copy(self):
465
        """Return a deep copy of self. All internal property maps are also
466
467
        copied."""
        return Graph(self)
468

469
470
471
472
473
474
475
476
477
478
479
    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()
480
        return "<Graph object, %s%s, with %d %s and %d edge%s%s at 0x%x>"\
481
482
483
               % (d, fr, n, "vertex" if n == 1 else "vertices", e,
                  "" if e == 1 else "s", f, id(self))

484
    # Graph access
485
    # ============
486
487

    def vertices(self):
488
        """Return an iterator over the vertices.
489
490
491
492
493
494
495
496
497
498
499
500

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

        """
501
        return libcore.get_vertices(weakref.ref(self.__graph))
502

503
504
505
506
507
508
509
    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
510
            v = libcore.get_vertex(weakref.ref(self.__graph), int(i))
511
512
513
514
        finally:
            if use_index:
                self.pop_filter(vertex=True)
        return v
515
516

    def edges(self):
517
        """Return an iterator over the edges."""
518
        return libcore.get_edges(weakref.ref(self.__graph))
519

520
    def add_vertex(self, n=1):
521
522
        """Add a vertex to the graph, and return it. If ``n > 1``, ``n``
        vertices are inserted and a list is returned."""
523
        vlist = [libcore.add_vertex(weakref.ref(self.__graph)) \
Tiago Peixoto's avatar
Tiago Peixoto committed
524
                 for i in xrange(0, n)]
525
        if n == 1:
526
527
            return vlist[0]
        return vlist
528

529
    def remove_vertex(self, vertex):
530
        """Remove a vertex from the graph."""
531
532
        index = self.vertex_index[vertex]
        for pmap in self.__known_properties:
533
534
535
            if pmap[0] == "v" and pmap[1]() != None and \
                   pmap[1]() != self.__vertex_index._PropertyMap__map:
                self.__graph.ShiftVertexProperty(pmap[1]().get_map(), index)
536
        self.clear_vertex(vertex)
537
        libcore.remove_vertex(self.__graph, vertex)
538

539
    def remove_vertex_if(self, predicate):
540
541
        """Remove all the vertices from the graph for which ``predicate(v)``
        evaluates to ``True``. """
542
543
544
545
546
547
        N = self.num_vertices()
        for i in xrange(0, N):
            v = self.vertex(N - i - 1)
            if predicate(v):
                self.remove_vertex(v)

548
    def clear_vertex(self, vertex):
549
        """Remove all in and out-edges from the given vertex."""
550
        del_es = set()
551
        for e in vertex.all_edges():
552
            del_es.add(e)
553
554
555
        for e in del_es:
            self.remove_edge(e)

556
    def add_edge(self, source, target):
557
        """Add a new edge from ``source`` to ``target`` to the graph, and return
558
        it."""
559
        return libcore.add_edge(weakref.ref(self.__graph), source, target)
560

561
    def remove_edge(self, edge):
562
        """Remove an edge from the graph."""
563
        return libcore.remove_edge(self.__graph, edge)
564

565
    def remove_edge_if(self, predicate):
566
567
        """Remove all edges from the graph, for which ``predicate(e)`` evaluates
        to ``True``."""
568
569
570
571
572
573
574
575
        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)

576
    def clear(self):
577
        """Remove all vertices and edges from the graph."""
578
579
        self.__graph.Clear()

580
    def clear_edges(self):
581
        """Remove all edges from the graph."""
582
583
584
585
586
587
588
589
        self.__graph.ClearEdges()

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

    # all properties
    def __get_properties(self):
        return PropertyDict(self, self.__properties,
Tiago Peixoto's avatar
Tiago Peixoto committed
590
591
592
                            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]))
593

Tiago Peixoto's avatar
Tiago Peixoto committed
594
    @_limit_args({"t": ["v", "e", "g"]})
595
596
597
598
599
    @_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
600
        self.__properties[(t, k)] = v
601

Tiago Peixoto's avatar
Tiago Peixoto committed
602
    @_limit_args({"t": ["v", "e", "g"]})
603
604
    @_require("k", str)
    def __del_property(self, t, k):
Tiago Peixoto's avatar
Tiago Peixoto committed
605
        del self.__properties[(t, k)]
606
607

    properties = property(__get_properties,
608
609
610
611
612
613
614
615
616
617
618
619
                          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")]
    """)
620
621

    def __get_specific_properties(self, t):
Tiago Peixoto's avatar
Tiago Peixoto committed
622
        props = dict([(k[1], v) for k,v in self.__properties.iteritems() \
623
624
625
626
                      if k[0] == t ])
        return props

    # vertex properties
627
    def __get_vertex_properties(self):
628
        return PropertyDict(self, self.__get_specific_properties("v"),
Tiago Peixoto's avatar
Tiago Peixoto committed
629
630
631
                            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))
632
633
    vertex_properties = property(__get_vertex_properties,
                                 doc="Dictionary of vertex properties")
Tiago Peixoto's avatar
Tiago Peixoto committed
634

635
    # edge properties
636
    def __get_edge_properties(self):
637
        return PropertyDict(self, self.__get_specific_properties("e"),
Tiago Peixoto's avatar
Tiago Peixoto committed
638
639
640
                            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))
641
642
643
    edge_properties = property(__get_edge_properties,
                                 doc="Dictionary of edge properties")

644
    # graph properties
645
    def __get_graph_properties(self):
646
        return PropertyDict(self, self.__get_specific_properties("g"),
Tiago Peixoto's avatar
Tiago Peixoto committed
647
648
649
                            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))
650
651
652
653
    graph_properties = property(__get_graph_properties,
                                 doc="Dictionary of graph properties")

    def list_properties(self):
654
        """List all internal properties.
655
656
657
658
659
660
661

        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")
662
        >>> g.graph_properties["gnat"] = g.new_graph_property("string", "hi there!")
663
664
665
666
667
668
669
        >>> g.list_properties()
        gnat           (graph)   (type: string, val: hi there!)
        bar            (vertex)  (type: python::object)
        foo            (vertex)  (type: double)
        foo            (edge)    (type: vector<double>)
        """

670
671
672
673
        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
674

Tiago Peixoto's avatar
Tiago Peixoto committed
675
        for k, v in self.__properties.iteritems():
676
677
678
            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
679
        for k, v in self.__properties.iteritems():
680
681
682
            if k[0] == "v":
                print "%%-%ds (vertex)  (type: %%s)" % w % (k[1],
                                                            v.value_type())
Tiago Peixoto's avatar
Tiago Peixoto committed
683
        for k, v in self.__properties.iteritems():
684
685
686
687
688
689
690
            if k[0] == "e":
                print "%%-%ds (edge)    (type: %%s)" % w % (k[1],
                                                            v.value_type())

    # index properties

    def _get_vertex_index(self):
691
        return self.__vertex_index
692
693
    vertex_index = property(_get_vertex_index,
                            doc="Vertex index map. This map is immutable.")
694
695

    def _get_edge_index(self):
696
        return self.__edge_index
697
    edge_index = property(_get_edge_index, doc="Edge index map.")
698
699
700

    # Property map creation

Tiago Peixoto's avatar
Tiago Peixoto committed
701
    def new_property(self, key_type, value_type):
702
        """Create a new (uninitialized) vertex property map of key type
Tiago Peixoto's avatar
Tiago Peixoto committed
703
704
        ``key_type`` (``v``, ``e`` or ``g``), value type ``value_type``, and
        return it.
705
        """
706
        if key_type == "v" or key_type == "vertex":
Tiago Peixoto's avatar
Tiago Peixoto committed
707
            return self.new_vertex_property(value_type)
708
        if key_type == "e" or key_type == "edge":
Tiago Peixoto's avatar
Tiago Peixoto committed
709
            return self.new_edge_property(value_type)
710
        if key_type == "g" or key_type == "graph":
Tiago Peixoto's avatar
Tiago Peixoto committed
711
            return self.new_graph_property(value_type)
Tiago Peixoto's avatar
Tiago Peixoto committed
712
        raise ValueError("unknown key type: " + key_type)
713

Tiago Peixoto's avatar
Tiago Peixoto committed
714
715
716
717
    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),
718
719
                                               self.__graph.GetVertexIndex()),
                           self, "v")
720

Tiago Peixoto's avatar
Tiago Peixoto committed
721
722
723
724
    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),
725
                                             self.__graph.GetEdgeIndex()),
726
727
                           self, "e")

Tiago Peixoto's avatar
Tiago Peixoto committed
728
729
730
731
    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),
732
733
                                              self.__graph.GetGraphIndex()),
                           self, "g", lambda k: k.__graph)
734
735
736
        if val != None:
            prop[self] = val
        return prop
737
738
739

    # property map copying
    @_require("src", PropertyMap)
740
    @_require("tgt", (PropertyMap, type(None)))
741
    def copy_property(self, src, tgt=None, value_type=None, g=None):
742
743
744
745
746
        """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).
747
        """
748
        if tgt == None:
749
750
751
            tgt = self.new_property(src.key_type(),
                                    (src.value_type()
                                     if value_type == None else value_type))
752
753
754
755
            ret = tgt
        else:
            ret = None

756
        if src.key_type() != tgt.key_type():
Tiago Peixoto's avatar
Tiago Peixoto committed
757
            raise ValueError("source and target properties must have the same" +
758
759
760
761
762
763
764
                             " key type")
        if g == None:
            g = self
        if g != self:
            g.stash_filter()
        self.stash_filter()
        if src.key_type() == "v":
765
766
            self.__graph.CopyVertexProperty(g.__graph, _prop("v", g, src),
                                            _prop("v", g, tgt))
767
        elif src.key_type() == "e":
768
769
            self.__graph.CopyEdgeProperty(g.__graph, _prop("e", g, src),
                                            _prop("e", g, tgt))
770
771
772
773
774
        else:
            tgt[self] = src[g]
        self.pop_filter()
        if g != self:
            g.pop_filter()
775
        return ret
776

777
    # degree property map
Tiago Peixoto's avatar
Tiago Peixoto committed
778
    @_limit_args({"deg": ["in", "out", "total"]})
779
780
    def degree_property_map(self, deg):
        """Create and return a vertex property map containing the degree type
781
        given by ``deg``."""
782
783
        return PropertyMap(self.__graph.DegreeMap(deg), self, "v")

784
785
    # I/O operations
    # ==============
Tiago Peixoto's avatar
Tiago Peixoto committed
786
787
788
789
790
791
792
793
794
795
796
797
798
799
    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"
800
            else:
Tiago Peixoto's avatar
Tiago Peixoto committed
801
802
803
804
805
                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)
806
        else:
807
            props = self.__graph.ReadFromFile("", file_name, file_format)
808
809
810
811
812
813
814
        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)
815

Tiago Peixoto's avatar
Tiago Peixoto committed
816
817
818
819
820
821
822
823
824
825
826
827
828
829
    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"
830
            else:
Tiago Peixoto's avatar
Tiago Peixoto committed
831
832
833
834
                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 \
835
                 self.__properties.iteritems()]
Tiago Peixoto's avatar
Tiago Peixoto committed
836
837
        if isinstance(file_name, str):
            self.__graph.WriteToFile(file_name, None, file_format, props)
838
        else:
Tiago Peixoto's avatar
Tiago Peixoto committed
839
            self.__graph.WriteToFile("", file_name, file_format, props)
840

841
842
    # Directedness
    # ============
843
844

    def set_directed(self, is_directed):
845
        """Set the directedness of the graph."""
846
847
848
        self.__graph.SetDirected(is_directed)

    def is_directed(self):
849
        """Get the directedness of the graph."""
850
851
        return self.__graph.GetDirected()

852
853
854
    # Reversedness
    # ============

855
    def set_reversed(self, is_reversed):
856
        """Reverse the direction of the edges, if ``reversed`` is ``True``, or
857
858
859
860
        maintain the original direction otherwise."""
        self.__graph.SetReversed(is_reversed)

    def is_reversed(self):
861
862
        """Return ``True`` if the edges are reversed, and ``False`` otherwise.
        """
863
864
        return self.__graph.GetReversed()

865
866
867
    # Filtering
    # =========

Tiago Peixoto's avatar
Tiago Peixoto committed
868
    def set_vertex_filter(self, prop, inverted=False):
869
        """Choose vertex boolean filter property. Only the vertices with value
870
871
872
873
874
        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
875
        self.__graph.SetVertexFilterProperty(_prop("v", self, prop),
876
                                             inverted)
Tiago Peixoto's avatar
Tiago Peixoto committed
877
        self.__filter_state["vertex_filter"] = (prop, inverted)
878
879

    def get_vertex_filter(self):
880
881
        """Return a tuple with the vertex filter property and bool value
        indicating whether or not it is inverted."""
882
        return self.__filter_state["vertex_filter"]
883

Tiago Peixoto's avatar
Tiago Peixoto committed
884
    def set_edge_filter(self, prop, inverted=False):
885
        """Choose edge boolean filter property. Only the edges with value
886
887
888
889
        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
890
891
        self.__graph.SetEdgeFilterProperty(_prop("e", self, prop), inverted)
        self.__filter_state["edge_filter"] = (prop, inverted)
892

893
    def get_edge_filter(self):
894
895
        """Return a tuple with the edge filter property and bool value
        indicating whether or not it is inverted."""
896
        return self.__filter_state["edge_filter"]
897
898
899

    def purge_vertices(self):
        """Remove all vertices of the graph which are currently being filtered
900
        out, and return it to the unfiltered state."""
901
        self.__graph.PurgeVertices()
902
        self.set_vertex_filter(None)
903
904
905

    def purge_edges(self):
        """Remove all edges of the graph which are currently being filtered out,
906
        and return it to the unfiltered state."""
907
        self.__graph.PurgeEdges()
908
        self.set_edge_filter(None)
909

910
911
912
913
914
    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."""
915
916
        if edge or vertex or directed or reversed:
            all = False
Tiago Peixoto's avatar
Tiago Peixoto committed
917
        self.__stashed_filter_state.append(self.get_filter_state())
918
        if libcore.graph_filtering_enabled():
919
920
921
922
923
924
925
926
927
            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
928
929
    def pop_filter(self, edge=False, vertex=False, directed=False,
                   reversed=False, all=True):
930
931
        """Pop last stashed filter state. The optional keyword arguments specify
        which type of filter should be recovered."""
932
933
        if edge or vertex or directed or reversed:
            all = False
934
935
936
937
938
939
940
941
942
943
944
945
        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"])
946

947
948
    def get_filter_state(self):
        """Return a copy of the filter state of the graph."""
Tiago Peixoto's avatar
Tiago Peixoto committed
949
950
        self.__filter_state["directed"] = self.is_directed()
        self.__filter_state["reversed"] = self.is_reversed()
951
952
953
954
        return copy.copy(self.__filter_state)

    def set_filter_state(self, state):
        """Set the filter state of the graph."""
955
956
957
958
959
        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])
960
961
962
        self.set_directed(state["directed"])
        self.set_reversed(state["reversed"])

963
    # Basic graph statistics
964
    # ======================
965
966
967
968
969
970

    def num_vertices(self):
        """Get the number of vertices."""
        return self.__graph.GetNumberOfVertices()

    def num_edges(self):
971
        """Get the number of edges."""
972
973
        return self.__graph.GetNumberOfEdges()

974
    # Pickling support
975
976
    # ================

977
978
979
    def __getstate__(self):
        state = dict()
        sio = StringIO()
Tiago Peixoto's avatar
Tiago Peixoto committed
980
981
982
983
984
985
986
987
988
        if libcore.graph_filtering_enabled():
            if self.get_vertex_filter()[0] != None:
                self.vertex_properties["_Graph__pickle__vfilter"] = \
                    self.get_vertex_filter()[0]
                state["vfilter"] = self.get_vertex_filter()[1]
            if self.get_edge_filter()[0] != None:
                self.edge_properties["_Graph__pickle__efilter"] = \
                    self.get_edge_filter()[0]
                state["efilter"] = self.get_edge_filter()[1]
989
990
991
        self.save(sio, "xml")
        state["blob"] = sio.getvalue()
        return state
Tiago Peixoto's avatar
Tiago Peixoto committed
992

993
994
995
996
997
998
    def __setstate__(self, state):
        self.__init__()
        blob = state["blob"]
        if blob != "":
            sio = StringIO(blob)
            self.load(sio, "xml")
Tiago Peixoto's avatar
Tiago Peixoto committed
999
        if "vfilt" in state:
Tiago Peixoto's avatar
Tiago Peixoto committed
1000
            vprop = self.vertex_properties["_Graph__pickle__vfilter"]