__init__.py 142 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-2020 Tiago de Paula Peixoto <tiago@skewed.de>
7
#
8
9
10
11
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
12
#
13
14
15
16
# 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 Lesser General Public License for more
# details.
17
#
18
19
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
20

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

Summary
-------

.. autosummary::
   :nosignatures:

   Graph
   GraphView
   Vertex
   Edge
35
36
37
   VertexPropertyMap
   EdgePropertyMap
   GraphPropertyMap
Tiago Peixoto's avatar
Tiago Peixoto committed
38
39
40
   PropertyMap
   PropertyArray
   load_graph
41
   load_graph_from_csv
Tiago Peixoto's avatar
Tiago Peixoto committed
42
43
   group_vector_property
   ungroup_vector_property
44
   map_property_values
45
   infect_vertex_property
46
   edge_endpoint_property
47
   incident_edges_op
Tiago Peixoto's avatar
Tiago Peixoto committed
48
   perfect_prop_hash
Tiago Peixoto's avatar
Tiago Peixoto committed
49
   value_types
50
51
52
53
54
   openmp_enabled
   openmp_get_num_threads
   openmp_set_num_threads
   openmp_get_schedule
   openmp_set_schedule
Tiago Peixoto's avatar
Tiago Peixoto committed
55
56
   show_config

Tiago Peixoto's avatar
Tiago Peixoto committed
57
58

This module provides:
59

60
   1. A :class:`~graph_tool.Graph` class for graph representation and manipulation
61
62
   2. Property maps for Vertex, Edge or Graph.
   3. Fast algorithms implemented in C++.
63

64
65
How to use the documentation
----------------------------
66

67
68
Documentation is available in two forms: docstrings provided
with the code, and the full documentation available in
Tiago Peixoto's avatar
Tiago Peixoto committed
69
`the graph-tool homepage <http://graph-tool.skewed.de>`_.
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

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
88
89
Contents
--------
90
"""
91

Tiago Peixoto's avatar
Tiago Peixoto committed
92
__author__ = "Tiago de Paula Peixoto <tiago@skewed.de>"
93
__copyright__ = "Copyright 2006-2020 Tiago de Paula Peixoto"
Tiago Peixoto's avatar
Tiago Peixoto committed
94
__license__ = "GPL version 3 or above"
Tiago Peixoto's avatar
Tiago Peixoto committed
95
__URL__ = "http://graph-tool.skewed.de"
96

97
98
99
100
# import numpy and scipy before everything to avoid weird segmentation faults
# depending on the order things are imported.

import numpy
101
import numpy.ma
102
103
import scipy

104
105
106

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

Tiago Peixoto's avatar
Tiago Peixoto committed
109
from . import gt_io  # sets up libcore io routines
Tiago Peixoto's avatar
Tiago Peixoto committed
110
111
112
113
114

import sys
import os
import re
import gzip
115
116
117
118
119
import bz2
try:
    import lzma
except ImportError:
    pass
Tiago Peixoto's avatar
Tiago Peixoto committed
120
121
import weakref
import copy
122
import textwrap
Tiago Peixoto's avatar
Tiago Peixoto committed
123
import io
124
import collections.abc
125
126
import itertools
import csv
Tiago Peixoto's avatar
Tiago Peixoto committed
127

Alex Henrie's avatar
Alex Henrie committed
128
from .decorators import _require, _limit_args, _copy_func
Tiago Peixoto's avatar
Tiago Peixoto committed
129

130
131
__all__ = ["Graph", "GraphView", "Vertex", "Edge", "VertexBase", "EdgeBase",
           "Vector_bool", "Vector_int16_t", "Vector_int32_t", "Vector_int64_t",
132
           "Vector_double", "Vector_long_double", "Vector_string",
Tiago Peixoto's avatar
Tiago Peixoto committed
133
134
135
136
137
138
139
140
           "Vector_size_t", "Vector_cdouble", "value_types", "load_graph",
           "load_graph_from_csv", "VertexPropertyMap", "EdgePropertyMap",
           "GraphPropertyMap", "PropertyMap", "PropertyArray",
           "group_vector_property", "ungroup_vector_property",
           "map_property_values", "infect_vertex_property",
           "edge_endpoint_property", "incident_edges_op", "perfect_prop_hash",
           "seed_rng", "show_config", "openmp_enabled",
           "openmp_get_num_threads", "openmp_set_num_threads",
141
142
           "openmp_get_schedule", "openmp_set_schedule", "__author__",
           "__copyright__", "__URL__", "__version__"]
Tiago Peixoto's avatar
Tiago Peixoto committed
143

Tiago Peixoto's avatar
Tiago Peixoto committed
144
145
# this is rather pointless, but it works around a sphinx bug
graph_tool = sys.modules[__name__]
Tiago Peixoto's avatar
Tiago Peixoto committed
146
147
148
149
150
151
152
153
154

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


def _prop(t, g, prop):
    """Return either a property map, or an internal property map with a given
    name."""
155
    if isinstance(prop, str):
Tiago Peixoto's avatar
Tiago Peixoto committed
156
157
158
159
160
161
162
163
        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
164
    if pmap is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
165
        return libcore.any()
166
167
168
169
    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()]))
170
171
172
173
174
175
    u = pmap.get_graph()
    if u is None:
        raise ValueError("Received orphaned property map")
    if g.base is not u.base:
        raise ValueError("Received property map for graph %s (base: %s), expected: %s (base: %s)" %
                         (str(g), str(g.base), str(u), str(u.base)))
176
    return pmap._get_any()
Tiago Peixoto's avatar
Tiago Peixoto committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196


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",
197
             "short": "int16_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
198
             "int": "int32_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
199
             "unsigned int": "int32_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
200
201
             "long": "int64_t",
             "long long": "int64_t",
202
             "unsigned long": "int64_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
203
204
205
206
             "object": "python::object",
             "float": "double"}
    if type_name in alias:
        return alias[type_name]
207
    if type_name in value_types():
208
        return type_name
Tiago Peixoto's avatar
Tiago Peixoto committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
    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
229
    if type_name == "string":
Tiago Peixoto's avatar
Tiago Peixoto committed
230
231
232
        return str
    return object

233
def _gt_type(obj):
234
235
236
237
238
    if isinstance(obj, numpy.dtype):
        t = obj.type
    else:
        t = type(obj)
    if issubclass(t, (numpy.int16, numpy.uint16, numpy.int8, numpy.uint8)):
239
        return "int16_t"
240
    if issubclass(t, (int, numpy.int32, numpy.uint32)):
241
        return "int32_t"
242
    if issubclass(t, (numpy.longlong, numpy.uint64, numpy.int64)):
243
        return "int64_t"
244
    if issubclass(t, (float, numpy.float, numpy.float16, numpy.float32, numpy.float64)):
245
        return "double"
246
    if issubclass(t, numpy.float128):
247
        return "long double"
248
    if issubclass(t, str):
249
        return "string"
250
    if issubclass(t, bool):
251
        return "bool"
252
    if issubclass(t, (list, numpy.ndarray)):
253
254
255
        return "vector<%s>" % _gt_type(obj[0])
    return "object"

256
def _converter(val_type):
257
258
    # attempt to convert to a compatible python type. This is useful,
    # for instance, when dealing with numpy types.
259
    vtype = _python_type(val_type)
260
    if type(vtype) is tuple:
261
262
263
264
265
        def convert(val):
            return [vtype[1](x) for x in val]
    elif vtype is object:
        def convert(val):
            return val
266
    elif vtype is str:
267
        return str
268
269
270
271
    else:
        def convert(val):
            return vtype(val)
    return convert
272

Tiago Peixoto's avatar
Tiago Peixoto committed
273
274
275
def show_config():
    """Show ``graph_tool`` build configuration."""
    info = libcore.mod_info()
276
277
278
279
280
281
282
283
    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
284

285
def terminal_size():
286
287
288
289
290
291
292
    try:
        import fcntl, termios, struct
        h, w, hp, wp = struct.unpack('HHHH',
            fcntl.ioctl(0, termios.TIOCGWINSZ,
            struct.pack('HHHH', 0, 0, 0, 0)))
    except IOError:
        w, h = 80, 100
293
294
    return w, h

295
296
297
298
299
try:
    libcore.mod_info("wrong")
except BaseException as e:
    ArgumentError = type(e)

Tiago Peixoto's avatar
Tiago Peixoto committed
300
301
302
303
304
################################################################################
# Property Maps
################################################################################

class PropertyMap(object):
305
    """This base class provides a mapping from vertices, edges or whole graphs to
306
    arbitrary properties.
Tiago Peixoto's avatar
Tiago Peixoto committed
307

308
309
310
    See :ref:`sec_property_maps` for more details.

    The possible property value types are listed below.
Tiago Peixoto's avatar
Tiago Peixoto committed
311
312
313
314
315
316
317

    .. table::

        =======================     ======================
         Type name                  Alias
        =======================     ======================
        ``bool``                    ``uint8_t``
318
        ``int16_t``                 ``short``
Tiago Peixoto's avatar
Tiago Peixoto committed
319
320
321
322
323
324
        ``int32_t``                 ``int``
        ``int64_t``                 ``long``, ``long long``
        ``double``                  ``float``
        ``long double``
        ``string``
        ``vector<bool>``            ``vector<uint8_t>``
325
        ``vector<int16_t>``         ``short``
Tiago Peixoto's avatar
Tiago Peixoto committed
326
327
328
329
330
331
332
333
        ``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``
        =======================     ======================
    """
334
    def __init__(self, pmap, g, key_type):
335
336
        if type(self) == PropertyMap:
            raise Exception("PropertyMap cannot be instantiated directly")
Tiago Peixoto's avatar
Tiago Peixoto committed
337
338
        self.__map = pmap
        self.__g = weakref.ref(g)
339
340
341
        self.__base_g = weakref.ref(g.base)  # keep reference to the
                                             # base graph, in case the
                                             # graph view is deleted.
Tiago Peixoto's avatar
Tiago Peixoto committed
342
        self.__key_type = key_type
343
        self.__convert = _converter(self.value_type())
Tiago Peixoto's avatar
Tiago Peixoto committed
344
345
        self.__register_map()

346
347
348
349
350
351
352
353
354
355
356
357
    def _get_any(self):
        t = self.key_type()
        g = self.get_graph()
        if t == "v":
            N = g.num_vertices(True)
        elif t == "e":
            N = g.edge_index_range
        else:
            N = 1
        self.reserve(N)
        return self.__map.get_map()

Tiago Peixoto's avatar
Tiago Peixoto committed
358
    def __register_map(self):
359
360
        for g in [self.__g(), self.__base_g()]:
            if g is not None:
361
                g._Graph__known_properties[id(self)] = weakref.ref(self)
Tiago Peixoto's avatar
Tiago Peixoto committed
362
363

    def __unregister_map(self):
364
        for g in [self.__g(), self.__base_g()]:
365
            if g is not None and id(self) in g._Graph__known_properties:
366
                del g._Graph__known_properties[id(self)]
Tiago Peixoto's avatar
Tiago Peixoto committed
367
368

    def __del__(self):
369
370
        if type(self) != PropertyMap:
            self.__unregister_map()
Tiago Peixoto's avatar
Tiago Peixoto committed
371
372
373
374
375
376
377
378
379

    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"
380
        g = self.get_graph()
381
        if g is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
382
383
384
            g = "a non-existent graph"
        else:
            g = "Graph 0x%x" % id(g)
385
        return ("<%sPropertyMap object with value type '%s',"
386
                + " for %s, at 0x%x>") % (k, self.value_type(), g, id(self))
Tiago Peixoto's avatar
Tiago Peixoto committed
387

388
389
390
391
392
393
394
395
396
    def copy(self, value_type=None, full=True):
        """Return a copy of the property map. If ``value_type`` is specified, the value
        type is converted to the chosen type. If ``full == False``, in the case
        of filtered graphs only the unmasked values are copied (with the
        remaining ones taking the type-dependent default value).

        """
        return self.get_graph().copy_property(self, value_type=value_type,
                                              full=full)
397

398
399
400
    def __copy__(self):
        return self.copy()

401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
    def __deepcopy__(self, memo):
        if self.value_type() != "python::object":
            return self.copy()
        else:
            pmap = self.copy()
            g = self.get_graph()
            if self.key_type() == "g":
                iters = [g]
            elif self.key_type() == "v":
                iters = g.vertices()
            else:
                iters = g.edges()
            for v in iters:
                pmap[v] = copy.deepcopy(self[v], memo)
            return pmap

417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    def coerce_type(self, full=True):
        """Return a copy of the property map with the most appropriate type, i.e. the
        simplest type necessary to accomodate all the values exactly. If ``full
        == False``, in the case of filtered graphs only the unmasked values are
        copied (with the remaining ones taking the type-dependent default
        value).
        """
        types = ["bool", "int16_t", "int32_t", "int64_t", "double",
                 "long double", "vector<bool>", "vector<int16_t>",
                 "vector<int32_t>", "vector<int64_t>", "vector<double>",
                 "vector<long double>", "string", "vector<string>"]
        for t in types:
            try:
                p = self.copy(value_type=t, full=full)
                if t == "bool":
                    a = p.a if full else p.fa
                    if p.a.max() > 1:
                        continue
                if p.copy(value_type=self.value_type(), full=full) == self:
                    break
            except (TypeError, ValueError, OverflowError):
                pass
        return p


Tiago Peixoto's avatar
Tiago Peixoto committed
442
443
    def get_graph(self):
        """Get the graph class to which the map refers."""
444
445
446
447
        g = self.__g()
        if g is None:
            g = self.__base_g()
        return g
Tiago Peixoto's avatar
Tiago Peixoto committed
448
449
450
451
452
453
454
455
456
457
458
459
460
461

    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):
462
463
        """Get a :class:`numpy.ndarray` subclass (:class:`~graph_tool.PropertyArray`)
        with the property values.
Tiago Peixoto's avatar
Tiago Peixoto committed
464

465
466
467
468
        .. 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
469
470
471
           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.
472
473

        .. warning::
Tiago Peixoto's avatar
Tiago Peixoto committed
474
475
476

           The returned array does not own the data, which belongs to the
           property map. Therefore, if the graph changes, the array may become
477
478
479
           *invalid*. Do **not** store the array if the graph is to be modified;
           store a **copy** instead.

Tiago Peixoto's avatar
Tiago Peixoto committed
480
        """
481
        return self._get_data()
Tiago Peixoto's avatar
Tiago Peixoto committed
482
483

    def __set_array(self, v):
484
        a = self.get_array()
485
486
487
        if a is None:
            raise TypeError("cannot set property map values from array for" +
                            " property map of type: " + self.value_type())
488
        a[:] = v
Tiago Peixoto's avatar
Tiago Peixoto committed
489

490
    a = property(get_array, __set_array,
Tiago Peixoto's avatar
Tiago Peixoto committed
491
                 doc=r"""Shortcut to the :meth:`~PropertyMap.get_array` method
492
493
494
495
                 as an attribute. This makes assignments more convenient, e.g.:

                 >>> g = gt.Graph()
                 >>> g.add_vertex(10)
Tiago Peixoto's avatar
Tiago Peixoto committed
496
                 <...>
497
498
499
500
501
502
503
504
505
506
507
508
                 >>> 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()
509
            N = g.num_vertices()
510
511
        elif self.__key_type == 'e':
            filt = g.get_edge_filter()
512
513
            if g.get_vertex_filter()[0] is not None:
                filt = (g.new_edge_property("bool"), filt[1])
514
                libcore.mark_edges(g._Graph__graph, _prop("e", g, filt[0]))
515
                if filt[1]:
516
                    filt[0].a = numpy.logical_not(filt[0].a)
517
            elif g.edge_index_range != g.num_edges():
518
                filt = (g.new_edge_property("bool"), False)
519
                libcore.mark_edges(g._Graph__graph, _prop("e", g, filt[0]))
520
            if filt[0] is None:
521
                N = g.edge_index_range
522
523
            else:
                N = (filt[0].a == (not filt[1])).sum()
524
        if get:
525
526
527
528
            if a is None:
                return a
            if filt[0] is None:
                return a
529
            return a[filt[0].a == (not filt[1])][:N]
530
        else:
531
            if a is None:
532
533
                raise TypeError("cannot set property map values from array for" +
                                " property map of type: " + self.value_type())
534
            if filt[0] is None:
535
536
537
538
                try:
                    a[:] = v
                except ValueError:
                    a[:] = v[:len(a)]
539
            else:
540
                m = filt[0].a == (not filt[1])
541
                m *= m.cumsum() <= N
542
543
544
545
                try:
                    a[m] = v
                except ValueError:
                    a[m] = v[:len(m)][m]
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569

    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()
570
571
            if g.get_vertex_filter()[0] is not None:
                filt = (g.new_edge_property("bool"), filt[1])
572
                libcore.mark_edges(g._Graph__graph, _prop("e", g, filt[0]))
573
574
                if filt[1]:
                    filt[0].a = 1 - filt[0].a
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
        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
592
                  :class:`~graph_tool.PropertyArray` is returned, which
593
                  is identical to the :attr:`~PropertyMap.a` attribute.""")
Tiago Peixoto's avatar
Tiago Peixoto committed
594

595
    def get_2d_array(self, pos):
596
597
598
599
600
601
        r"""Return a two-dimensional array of shape ``(M,N)``, where ``N`` is the number
        of vertices or edges, and ``M`` is the size of each property vector,
        with contains a copy of all 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 copied.
        """
602
603
604
605
606
607
608
609
610
611
612
613

        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()
614
615
            vfilt = g.get_vertex_filter()
            efilt = g.get_edge_filter()
616
617
618
            if self.key_type() == "v":
                iters = g.vertices()
            else:
619
620
621
622
623
624
                iters = [None for i in range(g.edge_index_range)]
                idx = g.edge_index
                for e in g.edges():
                    iters[idx[e]] = e
                iters = [e for e in iters if e is not None]
            a = [[] for i in range(len(p))]
625
626
            for v in iters:
                for i in range(len(p)):
627
                    a[i].append(p[i][v])
628
629
            a = numpy.array(a)
            return a
630

631
632
        p = ungroup_vector_property(self, pos)
        a = numpy.array([x.fa for x in p])
633
        return a
634
635

    def set_2d_array(self, a, pos=None):
636
637
638
639
640
641
642
        r"""Set the entries of the vector-valued property map from a two-dimensional
        array ``a`` of shape ``(M,N)``, where ``N`` is the number of vertices or
        edges, and ``M`` is the size of each property vector. If given, the
        parameter ``pos`` must be a sequence of integers which specifies the
        indexes of the property values which will be set (i.e. rows if the ``a``
        matrix).
        """
643
644
645
646
647
648
649
650
651
652
653
654
655
656

        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:
657
658
659
660
661
                    iters = [None for i in range(g.edge_index_range)]
                    idx = g.edge_index
                    for e in g.edges():
                        iters[idx[e]] = e
                    iters = [e for e in iters if e is not None]
662
663
                for j, v in enumerate(iters):
                    self[v] = a[j]
664
665
666
667
668
669
670
671
672
673
674
675
676
            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:
677
678
679
680
681
                    iters = [None for i in range(g.edge_index_range)]
                    idx = g.edge_index
                    for e in g.edges():
                        iters[idx[e]] = e
                    iters = [e for e in iters if e is not None]
682
683
684
685
                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
686
687
688
689
    def is_writable(self):
        """Return True if the property is writable."""
        return self.__map.is_writable()

690
691
692
693

    def set_value(self, val):
        """Sets all values in the property map to ``val``."""
        g = self.get_graph()
694
        val = self.__convert(val)
695
        if self.key_type() == "v":
696
            libcore.set_vertex_property(g._Graph__graph, _prop("v", g, self), val)
697
        elif self.key_type() == "e":
698
            libcore.set_edge_property(g._Graph__graph, _prop("e", g, self), val)
699
700
701
        else:
            self[g] = val

702
703
    def reserve(self, size):
        """Reserve enough space for ``size`` elements in underlying container. If the
704
           original size is already equal or larger, nothing will happen."""
705
706
        self.__map.reserve(size)

707
708
709
710
    def resize(self, size):
        """Resize the underlying container to contain exactly ``size`` elements."""
        self.__map.resize(size)

711
712
713
714
715
716
717
    def shrink_to_fit(self):
        """Shrink size of underlying container to accommodate only the necessary amount,
        and thus potentially freeing memory."""
        g = self.get_graph()
        if self.key_type() == "v":
            size = g.num_vertices(True)
        elif self.key_type() == "e":
718
            size = g.edge_index_range
719
720
721
722
723
        else:
            size = 1
        self.__map.resize(size)
        self.__map.shrink_to_fit()

Tiago Peixoto's avatar
Tiago Peixoto committed
724
725
726
727
728
729
730
731
    def swap(self, other):
        """Swap internal storage with ``other``."""
        if self.key_type() != other.key_type():
            raise ValueError("property maps must have the same key type")
        if self.value_type() != other.value_type():
            raise ValueError("property maps must have the same value type")
        self.__map.swap(other.__map)

732
733
734
735
    def data_ptr(self):
        """Return the pointer to memory where the data resides."""
        return self.__map.data_ptr()

736
737
    def __getstate__(self):
        g = self.get_graph()
738
739
        if g is None:
            raise ValueError("cannot pickle orphaned property map")
740
741
742
743
744
745
746
        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":
747
                vals = [self.__convert(self[v]) for v in u.vertices()]
748
            elif key_type == "e":
749
                vals = [self.__convert(self[e]) for e in u.edges()]
750
            else:
751
                vals = self.__convert(self[g])
752
753
754
755
756
757
758
759
760
761

        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"]
762
763
        key_type = state["key_type"]
        value_type = state["value_type"]
764
765
766
767
768
769
770
771
772
        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":
773
                pmap = u.new_vertex_property(value_type, vals=vals)
774
            elif key_type == "e":
775
                pmap = u.new_edge_property(value_type, vals=vals)
776
            else:
777
778
779
                pmap = u.new_graph_property(value_type)
                pmap[u] = vals
            pmap = g.own_property(pmap)
780
781
782
783
784

        self.__map = pmap.__map
        self.__g = pmap.__g
        self.__base_g = pmap.__base_g
        self.__key_type = key_type
Tiago Peixoto's avatar
Tiago Peixoto committed
785
        self.__convert = _converter(self.value_type())
786
787
        self.__register_map()

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
    # Guarantee pickle backward compatibility

    def __getitem__(self, k):
        if self.key_type() == "v":
            return VertexPropertyMap.__getitem__(self, k)
        if self.key_type() == "e":
            return EdgePropertyMap.__getitem__(self, k)
        if self.key_type() == "g":
            return GraphPropertyMap.__getitem__(self, k)

    def __setitem__(self, k, v):
        if self.key_type() == "v":
            VertexPropertyMap.__setitem__(self, k, v)
        if self.key_type() == "e":
            EdgePropertyMap.__setitem__(self, k, v)
        if self.key_type() == "g":
            GraphPropertyMap.__setitem__(self, k, v)

    def __iter__(self):
        if self.key_type() == "v":
            return VertexPropertyMap.__iter__(self)
        if self.key_type() == "e":
            return EdgePropertyMap.__iter__(self)
        if self.key_type() == "g":
            return GraphPropertyMap.__iter__(self)

    def _get_data(self):
        if self.key_type() == "v":
816
            return VertexPropertyMap._get_data(self)
817
        if self.key_type() == "e":
818
            return EdgePropertyMap._get_data(self)
819
        if self.key_type() == "g":
820
            return GraphPropertyMap._get_data(self)
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857


class VertexPropertyMap(PropertyMap):
    """This class provides a mapping from vertices to arbitrary properties.

    See :ref:`sec_property_maps` and :class:`PropertyMap` for more details.

    """

    def __init__(self, pmap, g):
        PropertyMap.__init__(self, pmap, g, "v")

    def __getitem__(self, k):
        return self._PropertyMap__map[int(k)]

    def __setitem__(self, k, v):
        k = int(k)
        try:
            self._PropertyMap__map[k] = v
        except TypeError:
            self._PropertyMap__map[k] = self._PropertyMap__convert(v)

    def __iter__(self):
        g = self.get_graph()
        for v in g.vertices():
            yield self[v]

    def _get_data(self):
        g = self.get_graph()
        if g is None:
            raise ValueError("Cannot get array for an orphaned property map")
        n = g._Graph__graph.get_num_vertices(False)
        a = self._PropertyMap__map.get_array(n)
        if a is None:
            return None
        return PropertyArray(a, self)

858
    def __eq__(self, other):
859
860
        if not isinstance(other, VertexPropertyMap):
            return False
861
862
863
864
865
866
867
        g = self.get_graph()
        if g.base is not other.get_graph().base:
            return False
        return libcore.compare_vertex_properties(g._Graph__graph,
                                                 self._get_any(),
                                                 other._get_any())

868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
class EdgePropertyMap(PropertyMap):
    """This class provides a mapping from edges to arbitrary properties.

    See :ref:`sec_property_maps` and :class:`PropertyMap` for more details.

    """

    def __init__(self, pmap, g):
        PropertyMap.__init__(self, pmap, g, "e")

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

    def __setitem__(self, k, v):
        try:
            self._PropertyMap__map[k] = v
        except TypeError:
885
            self._PropertyMap__map[k] = self._PropertyMap__convert(v)
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901

    def __iter__(self):
        g = self.get_graph()
        for e in g.edges():
            yield self[e]

    def _get_data(self):
        g = self.get_graph()
        if g is None:
            raise ValueError("Cannot get array for an orphaned property map")
        n = g.edge_index_range
        a = self._PropertyMap__map.get_array(n)
        if a is None:
            return None
        return PropertyArray(a, self)

902
    def __eq__(self, other):
903
904
        if not isinstance(other, EdgePropertyMap):
            return False
905
906
907
908
909
910
911
        g = self.get_graph()
        if g.base is not other.get_graph().base:
            return False
        return libcore.compare_edge_properties(g._Graph__graph,
                                               self._get_any(),
                                               other._get_any())

912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
class GraphPropertyMap(PropertyMap):
    """This class provides a mapping from graphs to arbitrary properties.

    See :ref:`sec_property_maps` and :class:`PropertyMap` for more details.

    """

    def __init__(self, pmap, g):
        PropertyMap.__init__(self, pmap, g, "g")

    def __getitem__(self, k):
        return self._PropertyMap__map[self.get_graph()._Graph__graph]

    def __setitem__(self, k, v):
        g = self.get_graph()._Graph__graph
        try:
            self._PropertyMap__map[g] = v
        except TypeError:
            self._PropertyMap__map[g] = self._PropertyMap__convert(v)

    def __iter__(self):
        return [self.get_graph()]

    def _get_data(self):
        g = self.get_graph()
        if g is None:
            raise ValueError("Cannot get array for an orphaned property map")
        a = self.__map.get_array(1)
        if a is None:
            return None
        return PropertyArray(a, self)


945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
class PropertyArray(numpy.ndarray):
    """This is a :class:`~numpy.ndarray` subclass which keeps a reference of its
    :class:`~graph_tool.PropertyMap` owner.
    """

    __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
        return obj
Tiago Peixoto's avatar
Tiago Peixoto committed
965
966
967
968

def _check_prop_writable(prop, name=None):
    if not prop.is_writable():
        raise ValueError("property map%s is not writable." %\
Tiago Peixoto's avatar
Tiago Peixoto committed
969
                         ((" '%s'" % name) if name is not None else ""))
Tiago Peixoto's avatar
Tiago Peixoto committed
970
971
972


def _check_prop_scalar(prop, name=None, floating=False):
973
    scalars = ["bool", "int16_t", "int32_t", "int64_t", "unsigned long",
Tiago Peixoto's avatar
Tiago Peixoto committed
974
975
976
977
978
979
               "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." %\
Tiago Peixoto's avatar
Tiago Peixoto committed
980
                         (((" '%s'" % name) if name is not None else ""),
Tiago Peixoto's avatar
Tiago Peixoto committed
981
982
983
984
                          (" floating" if floating else "")))


def _check_prop_vector(prop, name=None, scalar=True, floating=False):
985
    scalars = ["bool", "int16_t", "int32_t", "int64_t", "unsigned long",
Tiago Peixoto's avatar
Tiago Peixoto committed
986
987
988
989
990
991
992
993
               "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." %\
Tiago Peixoto's avatar
Tiago Peixoto committed
994
                         (((" '%s'" % name) if name is not None else ""),
Tiago Peixoto's avatar
Tiago Peixoto committed
995
996
997
998
999
1000
                          (" 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.

For faster browsing, not all history is shown. View entire blame