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

Tiago Peixoto's avatar
Tiago Peixoto committed
19
20
from dl_import import *
dl_import("import libgraph_tool_core as libcore")
21
__version__ = libcore.mod_info().version
22

23
import io # sets up libcore io routines
24

Tiago Peixoto's avatar
Tiago Peixoto committed
25
import sys, os, os.path, re, struct, fcntl, termios, gzip, bz2, string,\
26
       textwrap, time, signal, traceback, shutil, time, math, inspect, \
27
       functools, types, weakref
28
from StringIO import StringIO
29
from decorators import _wraps, _require, _attrs, _handle_exceptions, _limit_args
30
31
32
33
34

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

35
36
37
38
39
40
41
def _prop(t, g, prop):
    """Returns either a property map, or an internal vertex property map with a
    given name"""
    if type(prop) == str:
        try:
            pmap = g.properties[(t,prop)]
        except KeyError:
42
            raise GraphError("no internal %s property named: %s" %\
43
44
45
46
                             ("vertex" if t == "v" else \
                              ("edge" if t == "e" else "graph"),prop))
    else:
        pmap = prop
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    if pmap == None:
        return libcore.any()
    else:
        return pmap._PropertyMap__map.get_map()

def _degree(g, name):
    """Retrieve the degree type from string, or returns the corresponding
    property map"""
    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
65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
def _parse_range(range):
    """Parse a range in the form 'lower[*] upper[*]' (where an '*' indicates
    a closed boundary) or 'comp val', where 'comp' is [==|=|!=|>=|<=|>|<].
    """
    try:
        rcomp = re.compile(r"(>|<|>=|<=|==|=|!=)\s*([^=<>!]+)")
        rrange = re.compile(r"([^\*]+)(\*?)\s+([^\*]+)(\*?)")
        inverted = False
        if rcomp.match(range):
            comp = rcomp.match(range).group(1)
            thres = rcomp.match(range).group(2)
            thres = float(thres)
            if "<" in comp:
                ran = (float('-Inf'), thres)
                if "=" in comp:
                    inc = (False, True)
                else:
                    inc = (False, False)
            elif ">" in comp:
                ran = (thres, float('Inf'))
                if "=" in comp:
                    inc = (True, False)
                else:
                    inc = (False, False)
            elif comp == "==" or comp == "=" or comp == "!=":
                ran = (thres, thres)
                inc = (True, True)
                if comp == "!=":
                    inverted = True
        elif rrange.match(range):
            m = rrange.match(range)
            r1 = float(m.group(1))
            i1 = "*" in m.group(2)
            r2 = float(m.group(3))
            i2 = "*" in m.group(4)
            ran = (r1, r2)
            inc = (i1, i2)
        else:
            raise ValueError("invalid value for range: " + range)
    except (ValueError, TypeError), e:
        raise ValueError("invalid value for range: %s: %s " % (range, str(e)))
    return (ran, inc, inverted)

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

113
class PropertyMap(object):
114
    """Property map class"""
115
116
    def __init__(self, pmap, g, key_type, key_trans = None):
        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)))
127
    def __unregister_map(self):
128
129
130
131
132
        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]
133
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

    def get_graph(self):
144
        """Get the graph class to which the map refers"""
145
        return self.__g()
146
147
148
149
150
151
152
153
154

    def key_type(self):
        """The key type of the map. Either 'g', 'v' or 'e'"""
        return self.__key_type

    def value_type(self):
        """The value type of the map"""
        return self.__map.value_type()

155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    def get_array(self):
        """Get an array with property values

        .. WARNING::

           The returned array does not own the data, which belongs to the
           property map. Therefore, the returned array cannot have a longer
           lifespan than the property map itself! Futhermore, if the graph
           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*!
        """
        if self.__key_type == 'v':
            n = self.__g().num_vertices()
        elif self.__key_type == 'e':
            n = self.__g().num_edges()
        else:
            n = 1
        return self.__map.get_array(n)

175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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)
196
197
198
199
200
201

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

202
203
204
205
from libgraph_tool_core import Vertex, Edge, GraphError,\
     Vector_bool, Vector_int32_t,  Vector_int64_t, Vector_double,\
     Vector_long_double, Vector_string, new_vertex_property, new_edge_property,\
     new_graph_property
206
207

class Graph(object):
208
209
210
211
212
213
214
    """This class encapsulates either a directed multigraph (default) or an
    undirected multigraph, with optional internal edge, vertex or graph
    properties.

    ...

    """
215
216

    def __init__(self, g = None):
217
218
219
220
221
222
223
224
225
        self.__properties = {}
        self.__known_properties = []
        self.__filter_state = {"reversed": False,
                               "edge_filter": (None,False),
                               "vertex_filter": (None,False),
                               "directed": True,
                               "reversed": False}
        self.__stashed_filter_state = []

226
        if g == None:
227
            self.__graph = libcore.GraphInterface()
228
        else:
229
            self.__graph = libcore.GraphInterface(g.__graph)
230
231
232
            for k,v in g.__properties.iteritems():
                new_p = self.new_property(v.key_type(), v.value_type())
                self.copy_property(v, new_p, g)
233
                self.properties[k] = new_p
234
            self.__stashed_filter_state = [g.__filter_state]
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
            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:
                    for k,v in g.vertex_properties.iteritems():
                        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:
                    for k,v in g.edge_properties.iteritems():
                        if v == e_filt:
                            new_filt = self.edge_properties[k]
                self.__stashed_filter_state[0]["edge_filter"] = (new_filt,
                                                                 e_rev)
            self.pop_filter()
260
261
262
263
264
        # 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")
265
266
267

    @_handle_exceptions
    def copy(self):
268
269
270
        """Returns a deep copy of self. All internal property maps are also
        copied."""
        return Graph(self)
271
272

    # Graph access
273
    # ============
274
275
276

    @_handle_exceptions
    def vertices(self):
277
278
279
280
281
282
283
284
285
286
287
288
289
290
        """Return an iterator over the vertices

        Examples
        --------

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

        """
291
292
293
294
        return self.__graph.Vertices()

    @_handle_exceptions
    def vertex(self, i):
295
        """Return the i-th vertex from the graph."""
296
        return self.__graph.Vertex(int(i))
297
298
299

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

    @_handle_exceptions
304
305
306
307
308
309
310
    def add_vertex(self, n=1):
        """Add a vertices to the graph, and return it. If n > 1, n vertices are
        inserted and a list is returned."""
        if n == 1:
            return self.__graph.AddVertex()
        else:
            return [self.__graph.AddVertex() for i in xrange(0,n)]
311
312

    @_handle_exceptions
313
    def remove_vertex(self, vertex):
314
        """Remove a vertex from the graph."""
315
        k = vertex.in_degree() + vertex.out_degree()
316
317
        index = self.vertex_index[vertex]
        for pmap in self.__known_properties:
318
319
320
            if pmap[0] == "v" and pmap[1]() != None and \
                   pmap[1]() != self.__vertex_index._PropertyMap__map:
                self.__graph.ShiftVertexProperty(pmap[1]().get_map(), index)
321
322
323
324
325
        self.__graph.RemoveVertex(vertex)

    @_handle_exceptions
    def add_edge(self, source, target):
        """Add a new edge from 'source' to 'target' to the graph, and return
326
        it."""
327
328
329
        return self.__graph.AddEdge(source, target)

    @_handle_exceptions
330
    def remove_edge(self, edge):
331
        """Remove an edge from the graph."""
332
333
334
335
        self.__graph.RemoveEdge(edge)

    @_handle_exceptions
    def clear(self):
336
        """Remove all vertices and edges from the graph."""
337
338
        self.__graph.Clear()

339
340
    @_handle_exceptions
    def clear_edges(self):
341
        """Remove all edges from the graph."""
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
        self.__graph.ClearEdges()

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

    # all properties
    @_handle_exceptions
    def __get_properties(self):
        return PropertyDict(self, self.__properties,
                            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]))

    @_handle_exceptions
    @_limit_args({"t":["v", "e", "g"]})
    @_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")
        self.__properties[(t,k)] = v

    @_handle_exceptions
    @_limit_args({"t":["v", "e", "g"]})
    @_require("k", str)
    def __del_property(self, t, k):
        del self.__properties[(t,k)]

    properties = property(__get_properties,
371
372
373
374
375
376
377
378
379
380
381
382
                          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")]
    """)
383
384
385
386
387
388
389

    def __get_specific_properties(self, t):
        props = dict([(k[1],v) for k,v in self.__properties.iteritems() \
                      if k[0] == t ])
        return props

    # vertex properties
390
391
    @_handle_exceptions
    def __get_vertex_properties(self):
392
393
394
395
        return PropertyDict(self, self.__get_specific_properties("v"),
                            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))
396
397
    vertex_properties = property(__get_vertex_properties,
                                 doc="Dictionary of vertex properties")
398
    # edge properties
399
400
    @_handle_exceptions
    def __get_edge_properties(self):
401
402
403
404
        return PropertyDict(self, self.__get_specific_properties("e"),
                            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))
405
406
407
    edge_properties = property(__get_edge_properties,
                                 doc="Dictionary of edge properties")

408
    # graph properties
409
410
    @_handle_exceptions
    def __get_graph_properties(self):
411
412
413
414
415
416
417
418
419
        return PropertyDict(self, self.__get_specific_properties("g"),
                            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))
    graph_properties = property(__get_graph_properties,
                                 doc="Dictionary of graph properties")

    @_handle_exceptions
    def list_properties(self):
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        """List all internal properties for convenience.

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

436
437
438
439
        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
440

441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
        for k,v in self.__properties.iteritems():
            if k[0] == "g":
                print "%%-%ds (graph)   (type: %%s, val: %%s)" % w % \
                      (k[1], v.value_type(), str(v[self]))
        for k,v in self.__properties.iteritems():
            if k[0] == "v":
                print "%%-%ds (vertex)  (type: %%s)" % w % (k[1],
                                                            v.value_type())
        for k,v in self.__properties.iteritems():
            if k[0] == "e":
                print "%%-%ds (edge)    (type: %%s)" % w % (k[1],
                                                            v.value_type())

    # index properties

    def _get_vertex_index(self):
457
        return self.__vertex_index
458
459
    vertex_index = property(_get_vertex_index,
                            doc="Vertex index map. This map is immutable.")
460
461

    def _get_edge_index(self):
462
        return self.__edge_index
463
    edge_index = property(_get_edge_index, doc="Edge index map.")
464
465
466
467
468
469

    # Property map creation

    @_handle_exceptions
    def new_property(self, key_type, type):
        """Create a new (uninitialized) vertex property map of key type
470
471
        `key_type` (``v``, ``e`` or ``g``), value type ``type``, and return it.
        """
472
473
474
475
476
477
478
479
480
481
        if key_type == "v" or key_type == "vertex":
            return self.new_vertex_property(type)
        if key_type == "e" or key_type == "edge":
            return self.new_edge_property(type)
        if key_type == "g" or key_type == "graph":
            return self.new_graph_property(type)
        raise GraphError("unknown key type: " + key_type)

    @_handle_exceptions
    def new_vertex_property(self, type):
482
483
        """Create a new (uninitialized) vertex property map of type `type`, and
        return it."""
484
485
486
        return PropertyMap(new_vertex_property(type,
                                               self.__graph.GetVertexIndex()),
                           self, "v")
487

488
489
    @_handle_exceptions
    def new_edge_property(self, type):
490
491
        """Create a new (uninitialized) edge property map of type `type`, and
        return it."""
492
493
494
495
        return PropertyMap(new_edge_property(type, self.__graph.GetEdgeIndex()),
                           self, "e")

    @_handle_exceptions
496
497
498
499
    def new_graph_property(self, type, val=None):
        """Create a new graph property map of type `type`, and return it. If
        `val` is not None, the property is initialized to its value."""
        prop = PropertyMap(new_graph_property(type,
500
501
                                              self.__graph.GetGraphIndex()),
                           self, "g", lambda k: k.__graph)
502
503
504
        if val != None:
            prop[self] = val
        return prop
505
506
507
508
509
510

    # property map copying
    @_handle_exceptions
    @_require("src", PropertyMap)
    @_require("tgt", PropertyMap)
    def copy_property(self, src, tgt, g=None):
511
512
513
        """Copy contents of `src` property to `tgt` property. The optional
        parameter g specifices the (identical) source graph to copy properties
        from (defaults to self).
514
515
516
517
518
519
520
521
522
523
        """
        if src.key_type() != tgt.key_type():
            raise GraphError("source and target properties must have the same" +
                             " key type")
        if g == None:
            g = self
        if g != self:
            g.stash_filter()
        self.stash_filter()
        if src.key_type() == "v":
524
525
            self.__graph.CopyVertexProperty(g.__graph, _prop("v", g, src),
                                            _prop("v", g, tgt))
526
        elif src.key_type() == "e":
527
528
            self.__graph.CopyEdgeProperty(g.__graph, _prop("e", g, src),
                                            _prop("e", g, tgt))
529
530
531
532
533
534
535
536
        else:
            tgt[self] = src[g]
        self.pop_filter()
        if g != self:
            g.pop_filter()

    # I/O operations
    # ==============
537
538
539

    @_handle_exceptions
    def load(self, filename, format="auto"):
540
541
542
543
544
545
546
547
548
549
550
        """Load graph from 'filename' (which can also be a file-like
        object). The format is guessed from the file name, or can be specified
        by 'format', which can be either 'xml' or 'dot'."""
        if format == 'auto' and isinstance(filename, str):
            if filename.endswith(".xml") or filename.endswith(".xml.gz") or \
                   filename.endswith(".xml.bz2"):
                format = "xml"
            elif filename.endswith(".dot") or filename.endswith(".dot.gz") or \
                     filename.endswith(".dot.bz2"):
                format = "dot"
            else:
551
                libcore.raise_error\
552
553
554
555
                    ("cannot determine file format of: " + filename )
        elif format == "auto":
            format = "xml"
        if isinstance(filename, str):
556
            props = self.__graph.ReadFromFile(filename, None, format)
557
        else:
558
559
560
561
562
563
564
565
            props = self.__graph.ReadFromFile("", filename, format)
        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)
566
567
568
569
570

    @_handle_exceptions
    def save(self, filename, format="auto"):
        """Save graph to file. The format is guessed from the 'file' name, or
        can be specified by 'format', which can be either 'xml' or 'dot'."""
571
572
573
574
575
576
577
578
        if format == 'auto' and isinstance(filename, str):
            if filename.endswith(".xml") or filename.endswith(".xml.gz") or \
                   filename.endswith(".xml.bz2"):
                format = "xml"
            elif filename.endswith(".dot") or filename.endswith(".dot.gz") or \
                     filename.endswith(".dot.bz2"):
                format = "dot"
            else:
579
                libcore.raise_error\
580
581
582
                    ("cannot determine file format of: " + filename )
        elif format == "auto":
            format = "xml"
583
584
        props = [(name[1], prop._PropertyMap__map) for name,prop in \
                 self.__properties.iteritems()]
585
        if isinstance(filename, str):
586
            self.__graph.WriteToFile(filename, None, format, props)
587
        else:
588
            self.__graph.WriteToFile("", filename, format, props)
589

590
591
    # Directedness
    # ============
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612

    @_handle_exceptions
    def directed(self):
        """Treat graph as directed (default)."""
        self.__graph.SetDirected(True)

    @_handle_exceptions
    def undirected(self):
        """Treat graph as undirected."""
        self.__graph.SetDirected(False)

    @_handle_exceptions
    def set_directed(self, is_directed):
        """Set the directedness of the graph"""
        self.__graph.SetDirected(is_directed)

    @_handle_exceptions
    def is_directed(self):
        """Get the directedness of the graph"""
        return self.__graph.GetDirected()

613
614
615
    # Reversedness
    # ============

616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
    @_handle_exceptions
    def reversed(self):
        """Reverse the direction of the edges."""
        self.__graph.SetReversed(not self.__graph.GetReversed())

    @_handle_exceptions
    def set_reversed(self, is_reversed):
        """Reverse the direction of the edges, if 'reversed' is True, or
        maintain the original direction otherwise."""
        self.__graph.SetReversed(is_reversed)

    @_handle_exceptions
    def is_reversed(self):
        """Return 'True' if the edges are reversed, and 'False' otherwise."""
        return self.__graph.GetReversed()

632
633
634
    # Filtering
    # =========

635
636
    @_handle_exceptions
    def set_vertex_filter(self, property, inverted=False):
637
        """Choose vertex boolean filter property"""
638
        self.__graph.SetVertexFilterProperty(_prop("v", self, property), inverted)
639
        self.__filter_state["vertex_filter"] = (property, inverted)
640
641
642

    @_handle_exceptions
    def get_vertex_filter(self):
643
644
        """Get the vertex filter property and whether or not it is inverted"""
        return self.__filter_state["vertex_filter"]
645
646
647
648

    @_handle_exceptions
    def set_edge_filter(self, property, inverted=False):
        """Choose edge boolean property"""
649
        self.__graph.SetEdgeFilterProperty(_prop("e", self, property), inverted)
650
        self.__filter_state["edge_filter"] = (property, inverted)
651
652

    @_handle_exceptions
653
    def get_edge_filter(self):
654
655
        """Get the edge filter property and whether or not it is inverted"""
        return self.__filter_state["edge_filter"]
656
657
658
659
660
661

    @_handle_exceptions
    def purge_vertices(self):
        """Remove all vertices of the graph which are currently being filtered
        out, and return to the unfiltered state"""
        self.__graph.PurgeVertices()
662
        self.__graph.SetVertexFilterProperty(None)
663
664
665
666
667
668

    @_handle_exceptions
    def purge_edges(self):
        """Remove all edges of the graph which are currently being filtered out,
        and return to the unfiltered state"""
        self.__graph.PurgeEdges()
669
        self.__graph.SetEdgeFilterProperty(None)
670

671
672
673
674
    @_handle_exceptions
    def stash_filter(self):
        """Stash current filter state and recover unfiltered graph"""
        self.__stashed_filter_state.append(self.__filter_state)
675
676
677
        if libcore.graph_filtering_enabled():
            self.set_vertex_filter(None)
            self.set_edge_filter(None)
678
679
680
681
682
683
684
        self.directed()
        self.set_reversed(False)

    @_handle_exceptions
    def pop_filter(self):
        """Pop last stashed filter state"""
        state = self.__stashed_filter_state.pop()
685
686
687
688
689
        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])
690
691
692
693
        self.set_directed(state["directed"])
        self.set_reversed(state["reversed"])


694
    # Basic graph statistics
695
    # ======================
696
697
698
699
700
701
702
703
704
705
706

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

    @_handle_exceptions
    def num_edges(self):
        """Get the number of edges"""
        return self.__graph.GetNumberOfEdges()

707
    # Pickling support
708
709
    # ================

710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
    def __getstate__(self):
        state = dict()
        state["vertex_filt"] = self.get_vertex_filter()
        self.reset_vertex_filter()
        state["edge_filt"] = self.get_edge_filter()
        self.reset_edge_filter()
        sio = StringIO()
        self.save(sio, "xml")
        state["blob"] = sio.getvalue()
        return state
    def __setstate__(self, state):
        self.__init__()
        blob = state["blob"]
        if blob != "":
            sio = StringIO(blob)
            self.load(sio, "xml")
        if state["vertex_filt"] != None:
            self.set_vertex_filter(state["vertex_filt"][0],
                                   state["vertex_filt"][1])
        if state["edge_filt"] != None:
            self.set_edge_filter(state["edge_filt"][0],
                                 state["edge_filt"][1])

733
734
735
736
737
738
def load_graph(filename, format="auto"):
    """Load a graph from file"""
    g = Graph()
    g.load(filename, format=format)
    return g

739
740
def value_types():
    """Return a list of possible properties value types"""
741
    return libcore.get_property_types()