__init__.py 97.9 KB
Newer Older
1
#! /usr/bin/env python
2
# -*- coding: utf-8 -*-
3
#
4
5
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2015 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/>.

21
"""
Tiago Peixoto's avatar
Tiago Peixoto committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
graph_tool - efficient graph analysis and manipulation
======================================================

Summary
-------

.. autosummary::
   :nosignatures:

   Graph
   GraphView
   Vertex
   Edge
   PropertyMap
   PropertyArray
   load_graph
   group_vector_property
   ungroup_vector_property
40
   infect_vertex_property
41
   edge_endpoint_property
Tiago Peixoto's avatar
Tiago Peixoto committed
42
   perfect_prop_hash
Tiago Peixoto's avatar
Tiago Peixoto committed
43
44
45
   value_types
   show_config

Tiago Peixoto's avatar
Tiago Peixoto committed
46
47

This module provides:
48

49
   1. A :class:`~graph_tool.Graph` class for graph representation and manipulation
50
51
   2. Property maps for Vertex, Edge or Graph.
   3. Fast algorithms implemented in C++.
52

53
54
How to use the documentation
----------------------------
55

56
57
Documentation is available in two forms: docstrings provided
with the code, and the full documentation available in
Tiago Peixoto's avatar
Tiago Peixoto committed
58
`the graph-tool homepage <http://graph-tool.skewed.de>`_.
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

We recommend exploring the docstrings using `IPython
<http://ipython.scipy.org>`_, an advanced Python shell with TAB-completion and
introspection capabilities.

The docstring examples assume that ``graph_tool.all`` has been imported as
``gt``::

   >>> import graph_tool.all as gt

Code snippets are indicated by three greater-than signs::

   >>> x = x + 1

Use the built-in ``help`` function to view a function's docstring::

   >>> help(gt.Graph)

Tiago Peixoto's avatar
Tiago Peixoto committed
77
78
Contents
--------
79
"""
80

81
from __future__ import division, absolute_import, print_function
82
83
84
import sys
if sys.version_info < (3,):
    range = xrange
85

Tiago Peixoto's avatar
Tiago Peixoto committed
86
__author__ = "Tiago de Paula Peixoto <tiago@skewed.de>"
Tiago Peixoto's avatar
Tiago Peixoto committed
87
__copyright__ = "Copyright 2006-2015 Tiago de Paula Peixoto"
Tiago Peixoto's avatar
Tiago Peixoto committed
88
__license__ = "GPL version 3 or above"
Tiago Peixoto's avatar
Tiago Peixoto committed
89
__URL__ = "http://graph-tool.skewed.de"
90

91
92
93
94
# import numpy and scipy before everything to avoid weird segmentation faults
# depending on the order things are imported.

import numpy
95
import numpy.ma
96
97
98
import scipy
import scipy.stats

99
100
101

from .dl_import import *
dl_import("from . import libgraph_tool_core as libcore")
Tiago Peixoto's avatar
Tiago Peixoto committed
102
103
__version__ = libcore.mod_info().version

104
from . import io  # sets up libcore io routines
Tiago Peixoto's avatar
Tiago Peixoto committed
105
106
107
108
109
110
111

import sys
import os
import re
import gzip
import weakref
import copy
112
import textwrap
Tiago Peixoto's avatar
Tiago Peixoto committed
113
114
115
116
import io

if sys.version_info < (3,):
    import StringIO
Tiago Peixoto's avatar
Tiago Peixoto committed
117

118
from .decorators import _wraps, _require, _attrs, _limit_args
Tiago Peixoto's avatar
Tiago Peixoto committed
119
from inspect import ismethod
Tiago Peixoto's avatar
Tiago Peixoto committed
120
121

__all__ = ["Graph", "GraphView", "Vertex", "Edge", "Vector_bool",
122
123
124
125
126
           "Vector_int16_t", "Vector_int32_t", "Vector_int64_t",
           "Vector_double", "Vector_long_double", "Vector_string",
           "Vector_size_t", "value_types", "load_graph", "PropertyMap",
           "group_vector_property", "ungroup_vector_property",
           "infect_vertex_property", "edge_endpoint_property", "perfect_prop_hash",
Tiago Peixoto's avatar
Tiago Peixoto committed
127
128
           "seed_rng", "show_config", "PropertyArray", "openmp_enabled",
           "openmp_get_num_threads", "openmp_set_num_threads", "openmp_get_schedule",
129
           "openmp_set_schedule", "__author__", "__copyright__", "__URL__",
Tiago Peixoto's avatar
Tiago Peixoto committed
130
           "__version__"]
Tiago Peixoto's avatar
Tiago Peixoto committed
131

Tiago Peixoto's avatar
Tiago Peixoto committed
132
133
# this is rather pointless, but it works around a sphinx bug
graph_tool = sys.modules[__name__]
Tiago Peixoto's avatar
Tiago Peixoto committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

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


def _prop(t, g, prop):
    """Return either a property map, or an internal property map with a given
    name."""
    if type(prop) == str:
        try:
            pmap = g.properties[(t, prop)]
        except KeyError:
            raise KeyError("no internal %s property named: %s" %\
                           ("vertex" if t == "v" else \
                            ("edge" if t == "e" else "graph"), prop))
    else:
        pmap = prop
    if pmap == None:
        return libcore.any()
    else:
        if t != prop.key_type():
            names = {'e': 'edge', 'v': 'vertex', 'g': 'graph'}
            raise ValueError("Expected '%s' property map, got '%s'" %
                             (names[t], names[prop.key_type()]))
        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


def _type_alias(type_name):
    alias = {"int8_t": "bool",
             "boolean": "bool",
180
             "short": "int16_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
181
182
183
             "int": "int32_t",
             "long": "int64_t",
             "long long": "int64_t",
184
             "unsigned long": "int64_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
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
             "object": "python::object",
             "float": "double"}
    if type_name in value_types():
        return type_name
    if type_name in alias:
        return alias[type_name]
    ma = re.compile(r"vector<(.*)>").match(type_name)
    if ma:
        t = ma.group(1)
        if t in alias:
            return "vector<%s>" % alias[t]
    raise ValueError("invalid property value type: " + type_name)


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


216
217
218
219
def _gt_type(obj):
    t = type(obj)
    if t is numpy.longlong or t is numpy.uint64:
        return "long long"
220
221
    if issubclass(t, numpy.int16):
        return "short"
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    if t is int or issubclass(t, numpy.int):
        return "int"
    if t is numpy.float128:
        return "long double"
    if t is float or issubclass(t, numpy.float):
        return "double"
    if t is str:
        return "string"
    if t is bool:
        return "bool"
    if issubclass(t, list) or issubclass(t, numpy.ndarray):
        return "vector<%s>" % _gt_type(obj[0])
    return "object"


237
238
239
240
241
242
def _convert(prop, val):
    # attempt to convert to a compatible python type. This is useful,
    # for instance, when dealing with numpy types.
    vtype = _python_type(prop.value_type())
    if type(vtype) is tuple:
        return [vtype[1](x) for x in val]
243
244
    if vtype is object:
        return val
245
246
247
    return vtype(val)


Tiago Peixoto's avatar
Tiago Peixoto committed
248
249
250
def show_config():
    """Show ``graph_tool`` build configuration."""
    info = libcore.mod_info()
251
252
253
254
255
256
257
258
    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()))
Tiago Peixoto's avatar
Tiago Peixoto committed
259

260
261
262
263
264
265
266
def terminal_size():
    import fcntl, termios, struct
    h, w, hp, wp = struct.unpack('HHHH',
        fcntl.ioctl(0, termios.TIOCGWINSZ,
        struct.pack('HHHH', 0, 0, 0, 0)))
    return w, h

Tiago Peixoto's avatar
Tiago Peixoto committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
################################################################################
# Property Maps
################################################################################


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
294
            # do a copy
Tiago Peixoto's avatar
Tiago Peixoto committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
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
371
372
373
374
            obj = numpy.asarray(obj)

        return obj

    def _get_base(self):
        base = self
        while base.base is not None:
            base = base.base
        return base

    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__']:
        if hasattr(numpy.ndarray, method):
            locals()[method] = _wrap_method(method)


class PropertyMap(object):
    """This class provides a mapping from vertices, edges or whole graphs to arbitrary properties.

375
376
377
    See :ref:`sec_property_maps` for more details.

    The possible property value types are listed below.
Tiago Peixoto's avatar
Tiago Peixoto committed
378
379
380
381
382
383
384

    .. table::

        =======================     ======================
         Type name                  Alias
        =======================     ======================
        ``bool``                    ``uint8_t``
385
        ``int16_t``                 ``short``
Tiago Peixoto's avatar
Tiago Peixoto committed
386
387
388
389
390
391
        ``int32_t``                 ``int``
        ``int64_t``                 ``long``, ``long long``
        ``double``                  ``float``
        ``long double``
        ``string``
        ``vector<bool>``            ``vector<uint8_t>``
392
        ``vector<int16_t>``         ``short``
Tiago Peixoto's avatar
Tiago Peixoto committed
393
394
395
396
397
398
399
400
        ``vector<int32_t>``         ``vector<int>``
        ``vector<int64_t>``         ``vector<long>``, ``vector<long long>``
        ``vector<double>``          ``vector<float>``
        ``vector<long double>``
        ``vector<string>``
        ``python::object``          ``object``
        =======================     ======================
    """
401
    def __init__(self, pmap, g, key_type):
Tiago Peixoto's avatar
Tiago Peixoto committed
402
403
        self.__map = pmap
        self.__g = weakref.ref(g)
404
405
406
407
408
409
410
411
        self.__base_g = lambda: None
        try:
            if isinstance(g, GraphView):
                self.__base_g = weakref.ref(g.base)  # keep reference to the
                                                     # base graph, in case the
                                                     # graph view is deleted.
        except NameError:
            pass  # ignore if GraphView is yet undefined
Tiago Peixoto's avatar
Tiago Peixoto committed
412
413
414
        self.__key_type = key_type
        self.__register_map()

415
416
417
418
419
420
421
    def __key_trans(self, key):
        if self.key_type() == "g":
            return key._Graph__graph
        else:
            return key


Tiago Peixoto's avatar
Tiago Peixoto committed
422
    def __register_map(self):
423
424
        for g in [self.__g(), self.__base_g()]:
            if g is not None:
425
                g._Graph__known_properties[id(self)] = weakref.ref(self)
Tiago Peixoto's avatar
Tiago Peixoto committed
426
427

    def __unregister_map(self):
428
        for g in [self.__g(), self.__base_g()]:
429
            if g is not None and id(self) in g._Graph__known_properties:
430
                del g._Graph__known_properties[id(self)]
Tiago Peixoto's avatar
Tiago Peixoto committed
431
432
433
434
435
436
437
438
439
440
441
442

    def __del__(self):
        self.__unregister_map()

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

    def __setitem__(self, k, v):
        key = self.__key_trans(k)
        try:
            self.__map[key] = v
        except TypeError:
443
            self.__map[key] = _convert(self, v)
Tiago Peixoto's avatar
Tiago Peixoto committed
444
445
446
447
448
449
450
451
452

    def __repr__(self):
        # provide some more useful information
        if self.key_type() == "e":
            k = "Edge"
        elif self.key_type() == "v":
            k = "Vertex"
        else:
            k = "Graph"
453
        g = self.get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
454
455
456
457
        if g == None:
            g = "a non-existent graph"
        else:
            g = "Graph 0x%x" % id(g)
458
459
460
461
        try:
            vals = ", with values:\n%s" % str(self.fa)
        except ValueError:
            vals = ""
Tiago Peixoto's avatar
Tiago Peixoto committed
462
        return ("<PropertyMap object with key type '%s' and value type '%s',"
463
464
                + " for %s, at 0x%x%s>") % (k, self.value_type(), g, id(self),
                                            vals)
Tiago Peixoto's avatar
Tiago Peixoto committed
465

466
467
468
469
    def copy(self, value_type=None):
        """Return a copy of the property map. If ``value_type`` is specified,
        the value type is converted to the chosen type."""
        return self.get_graph().copy_property(self, value_type=value_type)
470

471
472
473
    def __copy__(self):
        return self.copy()

Tiago Peixoto's avatar
Tiago Peixoto committed
474
475
    def get_graph(self):
        """Get the graph class to which the map refers."""
476
477
478
479
        g = self.__g()
        if g is None:
            g = self.__base_g()
        return g
Tiago Peixoto's avatar
Tiago Peixoto committed
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495

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

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

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

    def get_array(self):
        """Get a :class:`~graph_tool.PropertyArray` with the property values.

496
497
498
499
        .. note::

           An array is returned *only if* the value type of the property map is
           a scalar. For vector, string or object types, ``None`` is returned
500
501
502
           instead. For vector and string objects, indirect array access is
           provided via the :func:`~graph_tool.PropertyMap.get_2d_array()` and
           :func:`~graph_tool.PropertyMap.set_2d_array()` member functions.
503
504

        .. warning::
Tiago Peixoto's avatar
Tiago Peixoto committed
505
506
507
508
509
510
511
512
513

           The returned array does not own the data, which belongs to the
           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.
        """
        a = self._get_data()
        if a is None:
514
            raise ValueError("Cannot get array for value type: " + self.value_type())
Tiago Peixoto's avatar
Tiago Peixoto committed
515
516
517
        return PropertyArray(a, prop_map=self)

    def _get_data(self):
518
519
        g = self.get_graph()
        if g is None:
520
            raise ValueError("Cannot get array for an orphaned property map")
Tiago Peixoto's avatar
Tiago Peixoto committed
521
        if self.__key_type == 'v':
522
            n = g._Graph__graph.GetNumberOfVertices(False)
Tiago Peixoto's avatar
Tiago Peixoto committed
523
        elif self.__key_type == 'e':
524
            n = g.max_edge_index
Tiago Peixoto's avatar
Tiago Peixoto committed
525
526
527
528
529
530
        else:
            n = 1
        a = self.__map.get_array(n)
        return a

    def __set_array(self, v):
531
532
        a = self.get_array()
        a[:] = v
Tiago Peixoto's avatar
Tiago Peixoto committed
533

534
    a = property(get_array, __set_array,
Tiago Peixoto's avatar
Tiago Peixoto committed
535
                 doc=r"""Shortcut to the :meth:`~PropertyMap.get_array` method
536
537
538
539
                 as an attribute. This makes assignments more convenient, e.g.:

                 >>> g = gt.Graph()
                 >>> g.add_vertex(10)
Tiago Peixoto's avatar
Tiago Peixoto committed
540
                 <...>
541
542
543
544
545
546
547
548
549
550
551
552
553
554
                 >>> prop = g.new_vertex_property("double")
                 >>> prop.a = np.random.random(10)           # Assignment from array
                 """)

    def __get_set_f_array(self, v=None, get=True):
        g = self.get_graph()
        if g is None:
            return None
        a = self.get_array()
        filt = [None]
        if self.__key_type == 'v':
            filt = g.get_vertex_filter()
        elif self.__key_type == 'e':
            filt = g.get_edge_filter()
555
556
557
            if g.get_vertex_filter()[0] is not None:
                filt = (g.new_edge_property("bool"), filt[1])
                u = GraphView(g, directed=True, skip_properties=True)
558
                libcore.mark_edges(u._Graph__graph, _prop("e", u, filt[0]))
559
560
                if filt[1]:
                    filt[0].a = 1 - filt[0].a
561
562
563
564
            elif g._get_max_edge_index() != g.num_edges():
                filt = (g.new_edge_property("bool"), False)
                u = GraphView(g, directed=True, skip_properties=True)
                libcore.mark_edges(u._Graph__graph, _prop("e", u, filt[0]))
565
        if get:
566
567
568
569
            if a is None:
                return a
            if filt[0] is None:
                return a
570
571
            return a[filt[0].a == (not filt[1])]
        else:
572
573
574
            if a is None:
                return
            if filt[0] is None:
575
576
577
578
                try:
                    a[:] = v
                except ValueError:
                    a[:] = v[:len(a)]
579
            else:
580
581
582
583
584
                m = filt[0].a == (not filt[1])
                try:
                    a[m] = v
                except ValueError:
                    a[m] = v[:len(m)][m]
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608

    fa = property(__get_set_f_array,
                  lambda self, v: self.__get_set_f_array(v, False),
                  doc=r"""The same as the :attr:`~PropertyMap.a` attribute, but
                  instead an *indexed* array is returned, which contains only
                  entries for vertices/edges which are not filtered out. If
                  there are no filters in place, the array is not indexed, and
                  is identical to the :attr:`~PropertyMap.a` attribute.

                  Note that because advanced indexing is triggered, a **copy**
                  of the array is returned, not a view, as for the
                  :attr:`~PropertyMap.a` attribute. Nevertheless, the assignment
                  of values to the *whole* array at once works as expected.""")

    def __get_set_m_array(self, v=None, get=True):
        g = self.get_graph()
        if g is None:
            return None
        a = self.get_array()
        filt = [None]
        if self.__key_type == 'v':
            filt = g.get_vertex_filter()
        elif self.__key_type == 'e':
            filt = g.get_edge_filter()
609
610
611
612
613
614
            if g.get_vertex_filter()[0] is not None:
                filt = (g.new_edge_property("bool"), filt[1])
                u = GraphView(g, directed=True, skip_properties=True)
                libcore.mark_edges(u._Graph__graph, _prop("e", g, filt[0]))
                if filt[1]:
                    filt[0].a = 1 - filt[0].a
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
        if filt[0] is None or a is None:
            if get:
                return a
            else:
                return
        ma = numpy.ma.array(a, mask=(filt[0].a == False) if not filt[1] else (filt[0].a == True))
        if get:
            return ma
        else:
            ma[:] = v

    ma = property(__get_set_m_array,
                  lambda self, v: self.__get_set_m_array(v, False),
                  doc=r"""The same as the :attr:`~PropertyMap.a` attribute, but
                  instead a :class:`~numpy.ma.MaskedArray` object is returned,
                  which contains only entries for vertices/edges which are not
                  filtered out. If there are no filters in place, a regular
                  :class:`~graph_tool.PropertyArray` is returned, which is
                  identical to the :attr:`~PropertyMap.a` attribute.""")
Tiago Peixoto's avatar
Tiago Peixoto committed
634

635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
    def get_2d_array(self, pos):
        r"""Return a two-dimensional array with a copy of the entries of the
        vector-valued property map. The parameter ``pos`` must be a sequence of
        integers which specifies the indexes of the property values which will
        be used. """

        if self.key_type() == "g":
            raise ValueError("Cannot create multidimensional array for graph property maps.")
        if "vector" not in self.value_type() and (len(pos) > 1 or pos[0] != 0):
            raise ValueError("Cannot create array of dimension %d (indexes %s) from non-vector property map of type '%s'." \
                             % (len(pos), str(pos), self.value_type()))
        if "string" in self.value_type():
            if "vector" in self.value_type():
                p = ungroup_vector_property(self, pos)
            else:
                p = [self]
            g = self.get_graph()
            if self.key_type() == "v":
                N = g.num_vertices()
            else:
                N = g.num_edges()
            a = [["" for j in range(N)] for i in range(len(p))]
            if self.key_type() == "v":
                iters = g.vertices()
            else:
                iters = g.edges()
            for v in iters:
                for i in range(len(p)):
                    a[i][int(v)] = p[i][v]
            if len(a) == 1:
                a = a[0]
            return numpy.array(a)
667
668
669
670

        try:
            return numpy.array(self.fa)
        except ValueError:
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
            p = ungroup_vector_property(self, pos)
            return numpy.array([x.a for x in p])

    def set_2d_array(self, a, pos=None):
        r"""Set the entries of the vector-valued property map from a
        two-dimensional array ``a``. If given, the parameter ``pos`` must be a
        sequence of integers which specifies the indexes of the property values
        which will be set."""

        if self.key_type() == "g":
            raise ValueError("Cannot set multidimensional array for graph property maps.")
        if "vector" not in self.value_type():
            if len(a.shape) != 1:
                raise ValueError("Cannot set array of shape %s to non-vector property map of type %s" % \
                                 (str(a.shape), self.value_type()))
            if self.value_type() != "string":
                self.fa = a
            else:
                g = self.get_graph()
                if self.key_type() == "v":
                    iters = g.vertices()
                else:
                    iters = g.edges()
                for i, v in enumerate(iters):
                    self[v] = a[i]
            return

        val = self.value_type()[7:-1]
        ps = []
        for i in range(a.shape[0]):
            ps.append(self.get_graph().new_property(self.key_type(), val))
            if self.value_type() != "string":
                ps[-1].fa = a[i]
            else:
                g = self.get_graph()
                if self.key_type() == "v":
                    iters = g.vertices()
                else:
                    iters = g.edges()
                for j, v in enumerate(iters):
                    ps[-1][v] = a[i, j]
        group_vector_property(ps, val, self, pos)

Tiago Peixoto's avatar
Tiago Peixoto committed
714
715
716
717
    def is_writable(self):
        """Return True if the property is writable."""
        return self.__map.is_writable()

718
719
720
721
722
    def __call__(self, a):
        p = self.copy()
        p.fa = a
        return p

723
724
    def __getstate__(self):
        g = self.get_graph()
725
726
        if g is None:
            raise ValueError("cannot pickle orphaned property map")
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
        value_type = self.value_type()
        key_type = self.key_type()
        if not self.is_writable():
            vals = None
        else:
            u = GraphView(g, skip_vfilt=True, skip_efilt=True)
            if key_type == "v":
                vals = [_convert(self, self[v]) for v in u.vertices()]
            elif key_type == "e":
                vals = [_convert(self, self[e]) for e in u.edges()]
            else:
                vals = _convert(self, self[g])

        state = dict(g=g, value_type=value_type,
                     key_type=key_type, vals=vals,
                     is_vindex=self is g.vertex_index,
                     is_eindex=self is g.edge_index)

        return state

    def __setstate__(self, state):
        g = state["g"]
        key_type = state["key_type"]
        value_type = state["value_type"]
        vals = state["vals"]

        if state["is_vindex"]:
            pmap = g.vertex_index
        elif state["is_eindex"]:
            pmap = g.edge_index
        else:
            u = GraphView(g, skip_vfilt=True, skip_efilt=True)
            if key_type == "v":
                pmap = g.new_vertex_property(value_type)
                for i, v in enumerate(u.vertices()):
                    pmap[v] = vals[i]
            elif key_type == "e":
                pmap = g.new_edge_property(value_type)
                for i, e in enumerate(u.edges()):
                    pmap[e] = vals[i]
            else:
                pmap = g.new_graph_property(value_type)
                pmap[g] = vals

        self.__map = pmap.__map
        self.__g = pmap.__g
        self.__base_g = pmap.__base_g
        self.__key_type = key_type
        self.__register_map()

Tiago Peixoto's avatar
Tiago Peixoto committed
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829

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 ""))


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 "")))


def _check_prop_vector(prop, name=None, scalar=True, floating=False):
    scalars = ["bool", "int32_t", "int64_t", "unsigned long",
               "double", "long double"]
    if not scalar:
        scalars += ["string"]
    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 "")))


def group_vector_property(props, value_type=None, vprop=None, pos=None):
    """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``.
830
831
832
833
834
835

    Examples
    --------
    >>> from numpy.random import seed, randint
    >>> from numpy import array
    >>> seed(42)
Tiago Peixoto's avatar
Tiago Peixoto committed
836
    >>> gt.seed_rng(42)
837
    >>> g = gt.random_graph(100, lambda: (3, 3))
838
839
    >>> props = [g.new_vertex_property("int") for i in range(3)]
    >>> for i in range(3):
840
841
    ...    props[i].a = randint(0, 100, g.num_vertices())
    >>> gprop = gt.group_vector_property(props)
842
    >>> print(gprop[g.vertex(0)].a)
Tiago Peixoto's avatar
Tiago Peixoto committed
843
    [51 25  8]
844
    >>> print(array([p[g.vertex(0)] for p in props]))
Tiago Peixoto's avatar
Tiago Peixoto committed
845
    [51 25  8]
Tiago Peixoto's avatar
Tiago Peixoto committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
    """
    g = props[0].get_graph()
    vtypes = set()
    keys = set()
    for i, p in enumerate(props):
        if "vector" in p.value_type():
            raise ValueError("property map 'props[%d]' is a vector property." %
                             i)
        vtypes.add(p.value_type())
        keys.add(p.key_type())
    if len(keys) > 1:
        raise ValueError("'props' must be of the same key type.")
    k = keys.pop()

    if vprop == None:
        if value_type == None and len(vtypes) == 1:
            value_type = vtypes.pop()

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

    for i, p in enumerate(props):
        if k != "g":
879
880
            u = GraphView(g, directed=True, reversed=g.is_reversed(),
                          skip_properties=True)
881
            libcore.group_vector_property(u._Graph__graph, _prop(k, g, vprop),
Tiago Peixoto's avatar
Tiago Peixoto committed
882
883
884
885
                                          _prop(k, g, p),
                                          i if pos == None else pos[i],
                                          k == 'e')
        else:
886
            vprop[g][i if pos is None else pos[i]] = p[g]
Tiago Peixoto's avatar
Tiago Peixoto committed
887
888
889
890
891
892
    return vprop


def ungroup_vector_property(vprop, pos, props=None):
    """Ungroup vector property map ``vprop`` into a list of individual property maps.

893
    Parameters
Tiago Peixoto's avatar
Tiago Peixoto committed
894
895
896
    ----------
    vprop : :class:`~graph_tool.PropertyMap`
        Vector property map to be ungrouped.
897
898
899
    pos : list of ints
        A list of indexes corresponding to where each element of ``vprop``
        should be inserted into the ungrouped list.
Tiago Peixoto's avatar
Tiago Peixoto committed
900
901
902
903
904
905
906
907
    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``.
908
909
910
911
912
913

    Examples
    --------
    >>> from numpy.random import seed, randint
    >>> from numpy import array
    >>> seed(42)
Tiago Peixoto's avatar
Tiago Peixoto committed
914
    >>> gt.seed_rng(42)
915
916
917
918
919
    >>> g = gt.random_graph(100, lambda: (3, 3))
    >>> prop = g.new_vertex_property("vector<int>")
    >>> for v in g.vertices():
    ...    prop[v] = randint(0, 100, 3)
    >>> uprops = gt.ungroup_vector_property(prop, [0, 1, 2])
920
    >>> print(prop[g.vertex(0)].a)
Tiago Peixoto's avatar
Tiago Peixoto committed
921
    [51 92 14]
922
    >>> print(array([p[g.vertex(0)] for p in uprops]))
Tiago Peixoto's avatar
Tiago Peixoto committed
923
    [51 92 14]
Tiago Peixoto's avatar
Tiago Peixoto committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
    """

    g = vprop.get_graph()
    _check_prop_vector(vprop, name="vprop", scalar=False)
    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]

    for i, p in enumerate(pos):
        if props[i].key_type() != k:
            raise ValueError("'props' must be of the same key type as 'vprop'.")

        if k != 'g':
943
944
945
            u = GraphView(g, directed=True, reversed=g.is_reversed(),
                          skip_properties=True)
            libcore.ungroup_vector_property(u._Graph__graph,
Tiago Peixoto's avatar
Tiago Peixoto committed
946
947
948
949
950
951
952
953
954
955
                                            _prop(k, g, vprop),
                                            _prop(k, g, props[i]),
                                            p, k == 'e')
        else:
            if len(vprop[g]) <= pos[i]:
                vprop[g].resize(pos[i] + 1)
            props[i][g] = vprop[g][pos[i]]
    return props


956
957
958
959
960
961
962
963
964
965
966
967
968
969
def infect_vertex_property(g, prop, vals=None):
    """Propagate the `prop` values of vertices with value `val` to all their
    out-neighbours.

    Parameters
    ----------
    prop : :class:`~graph_tool.PropertyMap`
        Property map to be modified.
    vals : list (optional, default: `None`)
        List of values to be propagated. If not provided, all values
        will be propagated.

    Returns
    -------
970
    None : ``None``
971
972
973
974
975

    Examples
    --------
    >>> from numpy.random import seed
    >>> seed(42)
Tiago Peixoto's avatar
Tiago Peixoto committed
976
    >>> gt.seed_rng(42)
977
    >>> g = gt.random_graph(100, lambda: (3, 3))
Tiago Peixoto's avatar
Tiago Peixoto committed
978
    >>> prop = g.vertex_index.copy("int32_t")
979
    >>> gt.infect_vertex_property(g, prop, [10])
980
    >>> print(sum(prop.a == 10))
Tiago Peixoto's avatar
Tiago Peixoto committed
981
    4
982
983
984
985
    """
    libcore.infect_vertex_property(g._Graph__graph, _prop("v", g, prop),
                                   vals)

Tiago Peixoto's avatar
Tiago Peixoto committed
986

987
988
989
990
@_limit_args({"endpoint": ["source", "target"]})
def edge_endpoint_property(g, prop, endpoint, eprop=None):
    """Return an edge property map corresponding to the vertex property `prop` of
    either the target and source of the edge, according to `endpoint`.
Tiago Peixoto's avatar
Tiago Peixoto committed
991
992
993
994

    Parameters
    ----------
    prop : :class:`~graph_tool.PropertyMap`
995
996
997
998
999
1000
        Vertex property map to be used to propagated to the edge.
    endpoint : `"source"` or `"target"`
        Edge endpoint considered. If the graph is undirected, the source is
        always the vertex with the lowest index.
    eprop : :class:`~graph_tool.PropertyMap` (optional, default: `None`)
        If provided, the resulting edge properties will be stored here.
Tiago Peixoto's avatar
Tiago Peixoto committed
1001
1002
1003

    Returns
    -------
1004
1005
    eprop : :class:`~graph_tool.PropertyMap`
        Propagated edge property.
Tiago Peixoto's avatar
Tiago Peixoto committed
1006
1007
1008

    Examples
    --------
Tiago Peixoto's avatar
Tiago Peixoto committed
1009
    >>> gt.seed_rng(42)
Tiago Peixoto's avatar
Tiago Peixoto committed
1010
    >>> g = gt.random_graph(100, lambda: (3, 3))
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
    >>> esource = gt.edge_endpoint_property(g, g.vertex_index, "source")
    >>> print(esource.a)
    [ 0  0  0 96 96 96 92 92 92 88 88 88 84 84 84 80 80 80 76 76 76 72 72 72 68
     68 68 64 64 64 60 60 60 56 56 56 52 52 52 48 48 48 44 44 44 40 40 40 36 36
     36 32 32 32 28 28 28 24 24 24 20 20 20 16 16 16 12 12 12  8  8  8  4  4  4
     99 99 99  1  1  1  2  2  2  3  3  3  5  5  5  6  6  6  7  7  7  9  9  9 10
     10 10 14 14 14 19 19 19 25 25 25 30 30 30 35 35 35 41 41 41 46 46 46 51 51
     51 57 57 57 62 62 62 67 67 67 73 73 73 78 78 78 83 83 83 89 89 89 94 94 94
     11 11 11 98 98 98 97 97 97 95 95 95 93 93 93 91 91 91 90 90 90 87 87 87 86
     86 86 85 85 85 82 82 82 81 81 81 79 79 79 77 77 77 75 75 75 74 74 74 71 71
     71 69 69 69 61 61 61 54 54 54 47 47 47 39 39 39 33 33 33 26 26 26 18 18 18
     70 70 70 13 13 13 15 15 15 17 17 17 21 21 21 22 22 22 23 23 23 27 27 27 29
     29 29 31 31 31 34 34 34 37 37 37 38 38 38 42 42 42 43 43 43 45 45 45 49 49
     49 50 50 50 53 53 53 55 55 55 58 58 58 59 59 59 63 63 63 65 65 65 66 66 66]
Tiago Peixoto's avatar
Tiago Peixoto committed
1025
    """
1026

Tiago Peixoto's avatar
Tiago Peixoto committed
1027
1028
    val_t = prop.value_type()
    if val_t == "unsigned long":
1029
1030
1031
1032
1033
        val_t = "int64_t"
    if eprop is None:
        eprop = g.new_edge_property(val_t)
    if eprop.value_type() != val_t:
        raise ValueError("'eprop' must be of the same value type as 'prop': " +
Tiago Peixoto's avatar
Tiago Peixoto committed
1034
                         val_t)
1035
1036
1037
    libcore.edge_endpoint(g._Graph__graph, _prop("v", g, prop),
                          _prop("e", g, eprop), endpoint)
    return eprop
Tiago Peixoto's avatar
Tiago Peixoto committed
1038

Tiago Peixoto's avatar
Tiago Peixoto committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
@_limit_args({"htype": ["int8_t", "int32_t", "int64_t"]})
def perfect_prop_hash(props, htype="int32_t"):
    """Given a list of property maps `props` of the same type, a derived list of
    property maps with integral type `htype` is retured, where each value is
    replaced by a perfect (i.e. unique) hash value.

    .. note::
       The hash value is deterministic, but it will not be necessarily the same
       for different values of `props`.
    """

    val_types = set([p.value_type() for p in props])
    if len(val_types) > 1:
        raise ValueError("All properties must have the same value type")
    hprops = [p.get_graph().new_property(p.key_type(), htype) for p in props]

    eprops = [p for p in props if p.key_type() == "e"]
    heprops = [p for p in hprops if p.key_type() == "e"]

    vprops = [p for p in props if p.key_type() == "v"]
    hvprops = [p for p in hprops if p.key_type() == "v"]

    hdict = libcore.any()

    for eprop, heprop in zip(eprops, heprops):
        g = eprop.get_graph()
1065
        g = GraphView(g, directed=True, skip_properties=True)
Tiago Peixoto's avatar
Tiago Peixoto committed
1066
1067
1068
1069
1070
        libcore.perfect_ehash(g._Graph__graph, _prop('e', g, eprop),
                              _prop('e', g, heprop), hdict)

    for vprop, hvprop in zip(vprops, hvprops):
        g = vprop.get_graph()
1071
        g = GraphView(g, directed=True, skip_properties=True)
Tiago Peixoto's avatar
Tiago Peixoto committed
1072
1073
1074
1075
        libcore.perfect_vhash(g._Graph__graph, _prop('v', g, vprop),
                              _prop('v', g, hvprop), hdict)

    return hprops
Tiago Peixoto's avatar
Tiago Peixoto committed
1076

Tiago Peixoto's avatar
Tiago Peixoto committed
1077
1078
class PropertyDict(dict):
    """Wrapper for the dict of vertex, graph or edge properties, which sets the
1079
1080
1081
1082
1083
1084
1085
1086
1087
    value on the property map when changed in the dict.

    .. note::

        The class is only an one-way proxy to the internally-kept properties. If
        you modify this object, the change will be propagated to the internal
        dictionary, but not vice-versa. Keep this in mind if you intend to keep
        a copy of the class instance.
    """
Tiago Peixoto's avatar
Tiago Peixoto committed
1088
1089
1090
1091
1092
1093
1094
1095
    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

1096
1097
1098
1099
    def __getitem__(self, key):
        if self.get_func != None:
            val = self.get_func(self.g, key)
            dict.__setitem__(self, key, val)
1100
            return val
1101
1102
1103
        else:
            raise KeyError("Property dict cannot be gotten")

Tiago Peixoto's avatar
Tiago Peixoto committed
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
    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)

Tiago Peixoto's avatar
Tiago Peixoto committed
1115
1116
1117
1118
1119
    def clear(self):
        for k in self.keys():
            self.del_func(self.g, k)
        dict.clear(self)

Tiago Peixoto's avatar
Tiago Peixoto committed
1120
1121
1122
1123
1124
################################################################################
# Graph class
# The main graph interface
################################################################################

1125
1126
1127
from .libgraph_tool_core import Vertex, EdgeBase, Vector_bool, Vector_int16_t, \
    Vector_int32_t, Vector_int64_t, Vector_double, Vector_long_double, \
    Vector_string, new_vertex_property, new_edge_property, new_graph_property
Tiago Peixoto's avatar
Tiago Peixoto committed
1128
1129
1130
1131
1132


class Graph(object):
    """Generic multigraph class.

1133
1134
    This class encapsulates either a directed multigraph (default or if
    ``directed=True``) or an undirected multigraph (if ``directed=False``),
1135
    with optional internal edge, vertex or graph properties.
Tiago Peixoto's avatar
Tiago Peixoto committed
1136
1137
1138
1139

    If ``g`` is specified, the graph (and its internal properties) will be
    copied.

1140
1141
1142
1143
1144
    If ``prune`` is set to ``True``, and ``g`` is specified, only the filtered
    graph will be copied, and the new graph object will not be
    filtered. Optionally, a tuple of three booleans can be passed as value to
    ``prune``, to specify a different behavior to vertex, edge, and reversal
    filters, respectively.
1145

1146
1147
1148
1149
    If ``vorder`` is specified, it should correspond to a vertex
    :class:`~graph_tool.PropertyMap` specifying the ordering of the vertices in
    the copied graph.

Tiago Peixoto's avatar
Tiago Peixoto committed
1150
1151
1152
1153
1154
1155
1156
    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

    """

1157
    def __init__(self, g=None, directed=True, prune=False, vorder=None):
Tiago Peixoto's avatar
Tiago Peixoto committed
1158
        self.__properties = {}
1159
        self.__known_properties = {}
Tiago Peixoto's avatar
Tiago Peixoto committed
1160
1161
1162
1163
        self.__filter_state = {"reversed": False,
                               "edge_filter": (None, False),
                               "vertex_filter": (None, False),
                               "directed": True}
1164
        if g is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1165
1166
            self.__graph = libcore.GraphInterface()
            self.set_directed(directed)
1167
1168
1169
1170
1171
1172
1173

            # 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")

Tiago Peixoto's avatar
Tiago Peixoto committed
1174
        else:
1175
1176
1177
1178
1179
            if isinstance(prune, bool):
                vprune = eprune = rprune = prune
            else:
                vprune, eprune, rprune = prune
            if not (vprune or eprune or rprune):
Tiago Peixoto's avatar
Tiago Peixoto committed
1180
1181
                gv = GraphView(g, skip_vfilt=True,
                               skip_efilt=True)
1182
                if not rprune:
Tiago Peixoto's avatar
Tiago Peixoto committed
1183
1184
1185
1186
1187
1188
1189
                    gv.set_reversed(False)
            else:
                gv = g

            # The filters may or may not not be in the internal property maps
            vfilt = g.get_vertex_filter()[0]
            efilt = g.get_edge_filter()[0]
1190

1191
1192
            if (vorder is None and ((vfilt is None and efilt is None) or
                                    (not vprune and not eprune))):
1193
1194
1195
                # Do a simpler, faster copy.
                self.__graph = libcore.GraphInterface(gv.__graph, False,
                                                      [], [], None)
1196
1197
1198
1199
1200
1201
1202

                # 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")

1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
                nvfilt = nefilt = None
                for k, m in g.properties.items():
                    nmap = self.copy_property(m, g=gv)
                    self.properties[k] = nmap
                    if m is vfilt:
                        nvfilt = nmap
                    if m is efilt:
                        nefilt = nmap
                if vfilt is not None:
                    if nvfilt is None:
                        nvfilt = self.copy_property(vfilt, g=gv)
                if efilt is not None:
                    if nefilt is None:
                        nefilt = self.copy_property(efilt, g=gv)
1217
1218
1219
                self.set_filters(nefilt, nvfilt,
                                 inverted_edges=g.get_edge_filter()[1],
                                 inverted_vertices=g.get_vertex_filter()[1])
1220
1221
1222
1223
1224
1225
1226
            else:

                # Copy all internal properties from original graph.
                vprops = []
                eprops = []
                ef_pos = vf_pos = None
                for k, m in gv.vertex_properties.items():
1227
1228
                    if not m.is_writable():
                        m = m.copy("int32_t")
1229
1230
1231
1232
                    if not vprune and m is vfilt:
                        vf_pos = len(vprops)
                    vprops.append([_prop("v", gv, m), libcore.any()])
                for k, m in gv.edge_properties.items():
1233
1234
                    if not m.is_writable():
                        m = m.copy("int32_t")
1235
                    if not eprune and m is efilt:
1236
1237
1238
                        ef_pos = len(eprops)
                    eprops.append([_prop("e", gv, m), libcore.any()])
                if not vprune and vf_pos is None and vfilt is not None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1239
                    vf_pos = len(vprops)
1240
1241
                    vprops.append([_prop("v", gv, vfilt), libcore.any()])
                if not eprune and ef_pos is None and efilt is not None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1242
                    ef_pos = len(eprops)
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
                    eprops.append([_prop("e", gv, efilt), libcore.any()])

                # The vertex ordering
                if vorder is None:
                    vorder = gv.new_vertex_property("int")
                    vorder.fa = numpy.arange(gv.num_vertices())

                # The actual copying of the graph and property maps
                self.__graph = libcore.GraphInterface(gv.__graph, False,
                                                      vprops,
                                                      eprops,
                                                      _prop("v", gv, vorder))
1255
1256
1257
1258
1259
                # 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")
1260
1261

                # Put the copied properties in the internal dictionary
1262
1263
                for i, (k, m) in enumerate(gv.vertex_properties.items()):
                    pmap = new_vertex_property(m.value_type() if m.is_writable() else "int32_t",
1264
1265
1266
1267
                                               self.__graph.GetVertexIndex(),
                                               vprops[i][1])
                    self.vertex_properties[k] = PropertyMap(pmap, self, "v")

1268
1269
                for i, (k, m) in enumerate(gv.edge_properties.items()):
                    pmap = new_edge_property(m.value_type() if m.is_writable() else "int32_t",
1270
1271
1272
1273
                                             self.__graph.GetEdgeIndex(),
                                             eprops[i][1])
                    self.edge_properties[k] = PropertyMap(pmap, self, "e")

1274
                for k, v in gv.graph_properties.items():
1275
                    new_p = self.new_graph_property(v.value_type())
1276
                    new_p[self] = v[gv]
1277
1278
                    self.graph_properties[k] = new_p

1279
                epmap = vpmap = None
1280
                if vf_pos is not None:
1281
1282
1283
                    vpmap = new_vertex_property("bool",
                                                self.__graph.GetVertexIndex(),
                                                vprops[vf_pos][1])
1284
                    vpmap = PropertyMap(vpmap, self, "v")
1285
                if ef_pos is not None:
1286
1287
1288
                    epmap = new_edge_property("bool",
                                              self.__graph.GetEdgeIndex(),
                                              eprops[ef_pos][1])
1289
                    epmap = PropertyMap(epmap, self, "e")
1290
1291
1292
                self.set_filters(epmap, vpmap,
                                 inverted_edges=g.get_edge_filter()[1],
                                 inverted_vertices=g.get_vertex_filter()[1])
1293

1294
            if not rprune:
1295
                self.set_reversed(g.is_reversed())
1296
1297

            # directedness is always a filter
1298
            self.set_directed(g.is_directed())
1299

Tiago Peixoto's avatar
Tiago Peixoto committed
1300
1301
1302
1303
1304
        # modification permissions
        self.__perms = {"add_edge": True, "del_edge": True,
                        "add_vertex": True, "del_vertex": True}

    def copy(self):
1305
1306
        """Return a deep copy of self. All :ref:`internal property maps <sec_internal_props>`
        are also copied."""
Tiago Peixoto's avatar
Tiago Peixoto committed
1307
1308
        return Graph(self)

1309
1310
1311
    def __copy__(self):
        return self.copy()

Tiago Peixoto's avatar
Tiago Peixoto committed
1312
    def __repr__(self):
1313
        # provide more useful information
Tiago Peixoto's avatar
Tiago Peixoto committed
1314
1315
1316
        d = "directed" if self.is_directed() else "undirected"
        fr = ", reversed" if self.is_reversed() and self.is_directed() else ""
        f = ""
1317
        if self.get_edge_filter()[0] is not None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1318
            f += ", edges filtered by %s" % (str(self.get_edge_filter()))
1319
        if self.get_vertex_filter()[0] is not None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
            f += ", vertices filtered by %s" % (str(self.get_vertex_filter()))
        n = self.num_vertices()
        e = self.num_edges()
        return "<%s object, %s%s, with %d %s and %d edge%s%s at 0x%x>"\
               % (type(self).__name__, d, fr, n,
                  "vertex" if n == 1 else "vertices", e, "" if e == 1 else "s",
                  f, id(self))

    # Graph access
    # ============

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

    def vertices(self):
1336
1337
1338
1339
1340
1341
1342
        """Return an :meth:`iterator <iterator.__iter__>` over the vertices.

        .. note::

           The order of the vertices traversed by the iterator **always**
           corresponds to the vertex index ordering, as given by the
           :attr:`~graph_tool.Graph.vertex_index` property map.
Tiago Peixoto's avatar
Tiago Peixoto committed
1343
1344
1345
1346

        Examples
        --------
        >>> g = gt.Graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
1347
        >>> vlist = list(g.add_vertex(5))
Tiago Peixoto's avatar
Tiago Peixoto committed
1348
1349
1350
1351
1352
1353
1354
        >>> vlist2 = []
        >>> for v in g.vertices():
        ...     vlist2.append(v)
        ...
        >>> assert(vlist == vlist2)

        """
1355
        return libcore.get_vertices(weakref.ref(self))
Tiago Peixoto's avatar
Tiago Peixoto committed
1356
1357
1358
1359
1360

    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). """
1361
        vfilt = self.get_vertex_filter()
1362
1363
        if vfilt[0] is None or not use_index:
            return libcore.get_vertex(weakref.ref(self), int(i))
Tiago Peixoto's avatar
Tiago Peixoto committed
1364
        try:
1365
            self.set_vertex_filter(None)
1366
            v = libcore.get_vertex(weakref.ref(self), int(i))
Tiago Peixoto's avatar
Tiago Peixoto committed
1367
        finally:
1368
            self.set_vertex_filter(vfilt[0], vfilt[1])
1369
1370
        if not v.is_valid():
            return v
1371
1372
        if vfilt[0] is not None and vfilt[0][v] == vfilt[1]:
            return None
Tiago Peixoto's avatar
Tiago Peixoto committed
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
        return v

    def edge(self, s, t, all_edges=False):
        """Return the edge from vertex ``s`` to ``t``, if it exists. If
        ``all_edges=True`` then a list is returned with all the parallel edges
        from ``s`` to ``t``, otherwise only one edge is returned.

        This operation will take :math:`O(k(s))` time, where :math:`k(s)` is the
        out-degree of vertex :math:`s`.
        """
        s = self.vertex(int(s))
        t = self.vertex(int(t))
1385
1386
1387
        if s is None or t is None:
            return None
        efilt = self.get_edge_filter()
Tiago Peixoto's avatar
Tiago Peixoto committed
1388
1389
        edges = []
        for e in s.out_edges():
1390
1391
            if efilt[0] is not None and efilt[0][e] == efilt[1]:
                continue
Tiago Peixoto's avatar
Tiago Peixoto committed
1392
1393
1394
1395
1396
1397
1398
1399
1400
            if e.target() == t:
                if not all_edges:
                    return e
                edges.append(e)
        if all_edges:
            return edges
        return None

    def edges(self):
1401
1402
1403
1404
1405
        """Return an :meth:`iterator <iterator.__iter__>` over the edges.

        .. note::

           The order of the edges traversed by the iterator **does not**
Tiago Peixoto's avatar
Tiago Peixoto committed
1406
           necessarily correspond to the edge index ordering, as given by the
1407
1408
1409
1410
1411
1412
1413
           :attr:`~graph_tool.Graph.edge_index` property map. This will only
           happen after :meth:`~graph_tool.Graph.reindex_edges` is called, or in
           certain situations such as just after a graph is loaded from a
           file. However, further manipulation of the graph may destroy the
           ordering.

        """
1414
        return libcore.get_edges(weakref.ref(self))
Tiago Peixoto's avatar
Tiago Peixoto committed
1415
1416

    def add_vertex(self, n=1):
1417
        """Add a vertex to the graph, and return it. If ``n != 1``, ``n``
1418
1419
1420
        vertices are inserted and an iterator over the new vertices is returned.
        This operation is :math:`O(n)`.
        """
1421
1422
1423
        if n == 0:
            return (None for i in range(0, 0))

Tiago Peixoto's avatar
Tiago Peixoto committed
1424
        self.__check_perms("add_vertex")
1425
1426
1427
1428
1429
1430
        v = libcore.add_vertex(weakref.ref(self), n)

        if n <= 1:
            return v
        else:
            pos = self.num_vertices() - n
1431
            return (self.vertex(i) for i in range(pos, pos + n))
Tiago Peixoto's avatar
Tiago Peixoto committed
1432

1433