__init__.py 116 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
   map_property_values
41
   infect_vertex_property
42
   edge_endpoint_property
43
   incident_edges_op
Tiago Peixoto's avatar
Tiago Peixoto committed
44
   perfect_prop_hash
Tiago Peixoto's avatar
Tiago Peixoto committed
45
46
47
   value_types
   show_config

Tiago Peixoto's avatar
Tiago Peixoto committed
48
49

This module provides:
50

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

55
56
How to use the documentation
----------------------------
57

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

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
79
80
Contents
--------
81
"""
82

83
from __future__ import division, absolute_import, print_function
84
85
86
import sys
if sys.version_info < (3,):
    range = xrange
87
88
else:
    unicode = str
89

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

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

import numpy
99
import numpy.ma
100
101
102
import scipy
import scipy.stats

103
104
105

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

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

import sys
import os
import re
import gzip
import weakref
import copy
116
import textwrap
Tiago Peixoto's avatar
Tiago Peixoto committed
117
import io
118
import collections
Tiago Peixoto's avatar
Tiago Peixoto committed
119
120
121

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

123
from .decorators import _wraps, _require, _attrs, _limit_args, _copy_func
Tiago Peixoto's avatar
Tiago Peixoto committed
124
from inspect import ismethod
Tiago Peixoto's avatar
Tiago Peixoto committed
125

126
127
__all__ = ["Graph", "GraphView", "Vertex", "Edge", "VertexBase", "EdgeBase",
           "Vector_bool", "Vector_int16_t", "Vector_int32_t", "Vector_int64_t",
128
129
130
           "Vector_double", "Vector_long_double", "Vector_string",
           "Vector_size_t", "value_types", "load_graph", "PropertyMap",
           "group_vector_property", "ungroup_vector_property",
131
132
133
134
135
136
           "map_property_values", "infect_vertex_property",
           "edge_endpoint_property", "incident_edges_op", "perfect_prop_hash",
           "seed_rng", "show_config", "PropertyArray", "openmp_enabled",
           "openmp_get_num_threads", "openmp_set_num_threads",
           "openmp_get_schedule", "openmp_set_schedule", "__author__",
           "__copyright__", "__URL__", "__version__"]
Tiago Peixoto's avatar
Tiago Peixoto committed
137

Tiago Peixoto's avatar
Tiago Peixoto committed
138
139
# this is rather pointless, but it works around a sphinx bug
graph_tool = sys.modules[__name__]
Tiago Peixoto's avatar
Tiago Peixoto committed
140
141
142
143
144
145
146
147
148

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


def _prop(t, g, prop):
    """Return either a property map, or an internal property map with a given
    name."""
149
    if isinstance(prop, (str, unicode)):
Tiago Peixoto's avatar
Tiago Peixoto committed
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
180
181
182
183
184
185
        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",
186
             "short": "int16_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
187
             "int": "int32_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
188
             "unsigned int": "int32_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
189
190
             "long": "int64_t",
             "long long": "int64_t",
191
             "unsigned long": "int64_t",
Tiago Peixoto's avatar
Tiago Peixoto committed
192
193
194
195
             "object": "python::object",
             "float": "double"}
    if type_name in alias:
        return alias[type_name]
196
197
    if type_name in value_types():
        return type_name
Tiago Peixoto's avatar
Tiago Peixoto committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    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
218
    if type_name == "string":
Tiago Peixoto's avatar
Tiago Peixoto committed
219
220
221
        return str
    return object

222
def _gt_type(obj):
223
224
225
226
227
    if isinstance(obj, numpy.dtype):
        t = obj.type
    else:
        t = type(obj)
    if issubclass(t, (numpy.int16, numpy.uint16, numpy.int8, numpy.uint8)):
228
        return "int16_t"
229
    if issubclass(t, (int, numpy.int32, numpy.uint32)):
230
        return "int32_t"
231
    if issubclass(t, (numpy.longlong, numpy.uint64, numpy.int64)):
232
        return "int64_t"
233
    if issubclass(t, (float, numpy.float, numpy.float16, numpy.float32, numpy.float64)):
234
        return "double"
235
    if issubclass(t, numpy.float128):
236
        return "long double"
237
    if issubclass(t, (str, unicode)):
238
        return "string"
239
    if issubclass(t, bool):
240
        return "bool"
241
    if issubclass(t, (list, numpy.ndarray)):
242
243
244
        return "vector<%s>" % _gt_type(obj[0])
    return "object"

245
def _converter(val_type):
246
247
    # attempt to convert to a compatible python type. This is useful,
    # for instance, when dealing with numpy types.
248
    vtype = _python_type(val_type)
249
    if type(vtype) is tuple:
250
251
252
253
254
        def convert(val):
            return [vtype[1](x) for x in val]
    elif vtype is object:
        def convert(val):
            return val
255
256
    elif vtype is str:
        return _c_str
257
258
259
260
    else:
        def convert(val):
            return vtype(val)
    return convert
261

Tiago Peixoto's avatar
Tiago Peixoto committed
262
263
264
def show_config():
    """Show ``graph_tool`` build configuration."""
    info = libcore.mod_info()
265
266
267
268
269
270
271
272
    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
273

274
def terminal_size():
275
276
277
278
279
280
281
    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
282
283
    return w, h

284
285
286
287
288
try:
    libcore.mod_info("wrong")
except BaseException as e:
    ArgumentError = type(e)

289
290
# Python 2 vs 3 compatibility

291
292
293
294
if sys.version_info < (3,):
    def _c_str(s):
        if isinstance(s, unicode):
            return s.encode("utf-8")
295
        return str(s)
296
297
    def _str_decode(s):
        return s
298
299
else:
    def _c_str(s):
300
        return str(s)
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
    def _str_decode(s):
        if isinstance(s, bytes):
            return s.decode("utf-8")
        return s

def get_bytes_io(buf=None):
    """We want BytesIO for python 3, but StringIO for python 2."""
    if sys.version_info < (3,):
        return StringIO.StringIO(buf)
    else:
        return io.BytesIO(buf)

def conv_pickle_state(state):
    """State keys may be of type `bytes` if python 3 is being used, but state was
    pickled with python 2."""

    if sys.version_info >= (3,):
        keys = [k for k in state.keys() if type(k) is bytes]
        for k in keys:
            state[k.decode("utf-8")] = state[k]
            del state[k]

323

Tiago Peixoto's avatar
Tiago Peixoto committed
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
################################################################################
# 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
351
            # do a copy
Tiago Peixoto's avatar
Tiago Peixoto committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
            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.

432
433
434
    See :ref:`sec_property_maps` for more details.

    The possible property value types are listed below.
Tiago Peixoto's avatar
Tiago Peixoto committed
435
436
437
438
439
440
441

    .. table::

        =======================     ======================
         Type name                  Alias
        =======================     ======================
        ``bool``                    ``uint8_t``
442
        ``int16_t``                 ``short``
Tiago Peixoto's avatar
Tiago Peixoto committed
443
444
445
446
447
448
        ``int32_t``                 ``int``
        ``int64_t``                 ``long``, ``long long``
        ``double``                  ``float``
        ``long double``
        ``string``
        ``vector<bool>``            ``vector<uint8_t>``
449
        ``vector<int16_t>``         ``short``
Tiago Peixoto's avatar
Tiago Peixoto committed
450
451
452
453
454
455
456
457
        ``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``
        =======================     ======================
    """
458
    def __init__(self, pmap, g, key_type):
Tiago Peixoto's avatar
Tiago Peixoto committed
459
460
        self.__map = pmap
        self.__g = weakref.ref(g)
461
462
463
464
465
466
467
468
        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
469
        self.__key_type = key_type
470
        self.__convert = _converter(self.value_type())
Tiago Peixoto's avatar
Tiago Peixoto committed
471
472
        self.__register_map()

473
474
475
476
477
478
    def __key_trans(self, key):
        if self.key_type() == "g":
            return key._Graph__graph
        else:
            return key

479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
    def __key_convert(self, k):
        if self.key_type() == "e":
            try:
                k = (int(k[0]), int(k[1]))
            except:
                raise ArgumentError
            key = self.__g().edge(k[0], k[1])
            if key is None:
                raise ValueError("Nonexistent edge: %s" % str(k))
        elif self.key_type() == "v":
            try:
                key = int(k)
            except:
                raise ArgumentError
            key = self.__g().vertex(key)
        return key
495

Tiago Peixoto's avatar
Tiago Peixoto committed
496
    def __register_map(self):
497
498
        for g in [self.__g(), self.__base_g()]:
            if g is not None:
499
                g._Graph__known_properties[id(self)] = weakref.ref(self)
Tiago Peixoto's avatar
Tiago Peixoto committed
500
501

    def __unregister_map(self):
502
        for g in [self.__g(), self.__base_g()]:
503
            if g is not None and id(self) in g._Graph__known_properties:
504
                del g._Graph__known_properties[id(self)]
Tiago Peixoto's avatar
Tiago Peixoto committed
505
506
507
508
509

    def __del__(self):
        self.__unregister_map()

    def __getitem__(self, k):
510
511
512
513
514
515
516
517
518
519
520
521
522
523
        k = self.__key_trans(k)
        try:
            return self.__map[k]
        except ArgumentError:
            try:
                k = self.__key_convert(k)
                return self.__map[k]
            except ArgumentError:
                if self.key_type() == "e":
                    kt = "Edge"
                elif self.key_type() == "v":
                    kt = "Vertex"
                else:
                    kt = "Graph"
524
525
                raise ValueError("invalid key '%s' of type '%s', wanted type: %s"
                                 % (str(k), str(type(k)), kt) )
Tiago Peixoto's avatar
Tiago Peixoto committed
526
527
528
529

    def __setitem__(self, k, v):
        key = self.__key_trans(k)
        try:
530
531
532
            try:
                self.__map[key] = v
            except TypeError:
533
                self.__map[key] = self.__convert(v)
534
535
536
537
538
539
        except ArgumentError:
            try:
                key = self.__key_convert(key)
                try:
                    self.__map[key] = v
                except TypeError:
540
                    self.__map[key] = self.__convert(v)
541
542
543
544
545
546
547
            except ArgumentError:
                if self.key_type() == "e":
                    kt = "Edge"
                elif self.key_type() == "v":
                    kt = "Vertex"
                else:
                    kt = "Graph"
548
549
550
551
552
                vt = self.value_type()
                raise ValueError("invalid key value pair '(%s, %s)' of types "
                                 "'(%s, %s)', wanted types: (%s, %s)" %
                                 (str(k), str(v), str(type(k)),
                                  str(type(v)), kt, vt))
Tiago Peixoto's avatar
Tiago Peixoto committed
553
554
555
556
557
558
559
560
561

    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"
562
        g = self.get_graph()
563
        if g is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
564
565
566
567
            g = "a non-existent graph"
        else:
            g = "Graph 0x%x" % id(g)
        return ("<PropertyMap object with key type '%s' and value type '%s',"
568
                + " for %s, at 0x%x>") % (k, self.value_type(), g, id(self))
Tiago Peixoto's avatar
Tiago Peixoto committed
569

570
571
572
573
574
575
576
577
578
    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)
579

580
581
582
    def __copy__(self):
        return self.copy()

583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
    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

Tiago Peixoto's avatar
Tiago Peixoto committed
599
600
    def get_graph(self):
        """Get the graph class to which the map refers."""
601
602
603
604
        g = self.__g()
        if g is None:
            g = self.__base_g()
        return g
Tiago Peixoto's avatar
Tiago Peixoto committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620

    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.

621
622
623
624
        .. 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
625
626
627
           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.
628
629

        .. warning::
Tiago Peixoto's avatar
Tiago Peixoto committed
630
631
632
633
634
635
636
637
638

           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:
639
            raise ValueError("Cannot get array for value type: " + self.value_type())
Tiago Peixoto's avatar
Tiago Peixoto committed
640
641
642
        return PropertyArray(a, prop_map=self)

    def _get_data(self):
643
644
        g = self.get_graph()
        if g is None:
645
            raise ValueError("Cannot get array for an orphaned property map")
Tiago Peixoto's avatar
Tiago Peixoto committed
646
        if self.__key_type == 'v':
647
            n = g._Graph__graph.get_num_vertices(False)
Tiago Peixoto's avatar
Tiago Peixoto committed
648
        elif self.__key_type == 'e':
649
            n = g.edge_index_range
Tiago Peixoto's avatar
Tiago Peixoto committed
650
651
652
653
654
655
        else:
            n = 1
        a = self.__map.get_array(n)
        return a

    def __set_array(self, v):
656
657
        a = self.get_array()
        a[:] = v
Tiago Peixoto's avatar
Tiago Peixoto committed
658

659
    a = property(get_array, __set_array,
Tiago Peixoto's avatar
Tiago Peixoto committed
660
                 doc=r"""Shortcut to the :meth:`~PropertyMap.get_array` method
661
662
663
664
                 as an attribute. This makes assignments more convenient, e.g.:

                 >>> g = gt.Graph()
                 >>> g.add_vertex(10)
Tiago Peixoto's avatar
Tiago Peixoto committed
665
                 <...>
666
667
668
669
670
671
672
673
674
675
676
677
                 >>> 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()
678
            N = g.num_vertices()
679
680
        elif self.__key_type == 'e':
            filt = g.get_edge_filter()
681
682
            if g.get_vertex_filter()[0] is not None:
                filt = (g.new_edge_property("bool"), filt[1])
683
                libcore.mark_edges(g._Graph__graph, _prop("e", g, filt[0]))
684
                if filt[1]:
685
                    filt[0].a = numpy.logical_not(filt[0].a)
686
            elif g.edge_index_range != g.num_edges():
687
                filt = (g.new_edge_property("bool"), False)
688
                libcore.mark_edges(g._Graph__graph, _prop("e", g, filt[0]))
689
            if filt[0] is None:
690
                N = g.edge_index_range
691
692
            else:
                N = (filt[0].a == (not filt[1])).sum()
693
        if get:
694
695
696
697
            if a is None:
                return a
            if filt[0] is None:
                return a
698
            return a[filt[0].a == (not filt[1])][:N]
699
        else:
700
701
702
            if a is None:
                return
            if filt[0] is None:
703
704
705
706
                try:
                    a[:] = v
                except ValueError:
                    a[:] = v[:len(a)]
707
            else:
708
                m = filt[0].a == (not filt[1])
709
                m *= m.cumsum() <= N
710
711
712
713
                try:
                    a[m] = v
                except ValueError:
                    a[m] = v[:len(m)][m]
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737

    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()
738
739
            if g.get_vertex_filter()[0] is not None:
                filt = (g.new_edge_property("bool"), filt[1])
740
                libcore.mark_edges(g._Graph__graph, _prop("e", g, filt[0]))
741
742
                if filt[1]:
                    filt[0].a = 1 - filt[0].a
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
        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
762

763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    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()
780
781
782
783
            vfilt = g.get_vertex_filter()
            efilt = g.get_edge_filter()
            if vfilt[0] is not None:
                g = GraphView(g, skip_vfilt=True, skip_efilt=True)
784
785
            if self.key_type() == "v":
                N = g.num_vertices()
786
787
                idx = g.vertex_index
                filt = vfilt
788
            else:
789
                N = g.edge_index_range
790
791
                idx = g.edge_index
                filt = efilt
792
793
794
795
796
797
798
            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)):
799
                    a[i][idx[v]] = p[i][v]
800
801
            if len(a) == 1:
                a = a[0]
802
803
804
805
            a = numpy.array(a)
            if vfilt[0] is not None:
                a = a[filt[0].a[:a.shape[0]] == (not filt[1])]
            return a
806
807
808
809

        try:
            return numpy.array(self.fa)
        except ValueError:
810
            p = ungroup_vector_property(self, pos)
811
            return numpy.array([x.fa for x in p])
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831

    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:
832
833
834
                    iters = sorted(g.edges(), key=lambda e: g.edge_index[e])
                for j, v in enumerate(iters):
                    self[v] = a[j]
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
            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
853
854
855
856
    def is_writable(self):
        """Return True if the property is writable."""
        return self.__map.is_writable()

857
858
859
860
861
862
863
864
865
866
867

    def set_value(self, val):
        """Sets all values in the property map to ``val``."""
        g = self.get_graph()
        if self.key_type() == "v":
            libcore.set_vertex_property(g._Graph__graph, self.__map.get_map(), val)
        elif self.key_type() == "e":
            libcore.set_edge_property(g._Graph__graph, self.__map.get_map(), val)
        else:
            self[g] = val

868
869
870
871
872
873
874
875
876
877
878
879
880
    def reserve(self, size):
        """Reserve enough space for ``size`` elements in underlying container. If the
           original size is larger, it will be reduced, and the remaining memory
           will be freed."""
        self.__map.reserve(size)

    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":
881
            size = g.edge_index_range
882
883
884
885
886
        else:
            size = 1
        self.__map.resize(size)
        self.__map.shrink_to_fit()

887
888
889
890
891
    def __call__(self, a):
        p = self.copy()
        p.fa = a
        return p

892
893
    def __getstate__(self):
        g = self.get_graph()
894
895
        if g is None:
            raise ValueError("cannot pickle orphaned property map")
896
897
898
899
900
901
902
        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":
903
                vals = [self.__convert(self[v]) for v in u.vertices()]
904
            elif key_type == "e":
905
                vals = [self.__convert(self[e]) for e in u.edges()]
906
            else:
907
                vals = self.__convert(self[g])
908
909
910
911
912
913
914
915
916

        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):
917
        conv_pickle_state(state)
918
        g = state["g"]
919
920
        key_type = _str_decode(state["key_type"])
        value_type = _str_decode(state["value_type"])
921
922
923
924
925
926
927
928
929
        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":
930
                pmap = u.new_vertex_property(value_type, vals=vals)
931
            elif key_type == "e":
932
                pmap = u.new_edge_property(value_type, vals=vals)
933
            else:
934
935
936
                pmap = u.new_graph_property(value_type)
                pmap[u] = vals
            pmap = g.own_property(pmap)
937
938
939
940
941

        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
942
        self.__convert = _converter(self.value_type())
943
944
        self.__register_map()

Tiago Peixoto's avatar
Tiago Peixoto committed
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997

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``.
998
999
1000

    Examples
    --------