__init__.py 68.1 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1001
1002
1003
1004
1005
1006
        >>> for v in g.vertices():
        ...     vlist2.append(v)
        ...
        >>> assert(vlist == vlist2)

        """
1007
        return libcore.get_vertices(weakref.ref(self))
Tiago Peixoto's avatar
Tiago Peixoto committed
1008
1009
1010
1011
1012
1013
1014
1015

    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). """
        if use_index:
            self.stash_filter(vertex=True)
        try:
1016
            v = libcore.get_vertex(weakref.ref(self), int(i))
Tiago Peixoto's avatar
Tiago Peixoto committed
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
        finally:
            if use_index:
                self.pop_filter(vertex=True)
        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))
        edges = []
        for e in s.out_edges():
            if e.target() == t:
                if not all_edges:
                    return e
                edges.append(e)
        if all_edges:
            return edges
        return None

    def edges(self):
1043
1044
1045
1046
1047
        """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
1048
           necessarily correspond to the edge index ordering, as given by the
1049
1050
1051
1052
1053
1054
1055
           :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.

        """
1056
        return libcore.get_edges(weakref.ref(self))
Tiago Peixoto's avatar
Tiago Peixoto committed
1057
1058
1059
1060
1061

    def add_vertex(self, n=1):
        """Add a vertex to the graph, and return it. If ``n > 1``, ``n``
        vertices are inserted and a list is returned."""
        self.__check_perms("add_vertex")
1062
1063
1064
        vlist = []
        vfilt = self.get_vertex_filter()
        for i in xrange(n):
1065
            v = libcore.add_vertex(weakref.ref(self))
1066
1067
1068
            if vfilt[0] is not None:
                vfilt[0][v] = not vfilt[1]
            vlist.append(v)
Tiago Peixoto's avatar
Tiago Peixoto committed
1069
1070
1071
1072
1073
1074
1075
1076
1077
        if n == 1:
            return vlist[0]
        return vlist

    def remove_vertex(self, vertex):
        """Remove a vertex from the graph."""
        self.__check_perms("del_vertex")
        index = self.vertex_index[vertex]
        for pmap in self.__known_properties:
1078
            if pmap[0] == "v" and pmap[1]() != None and pmap[1]().is_writable():
Tiago Peixoto's avatar
Tiago Peixoto committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
                self.__graph.ShiftVertexProperty(pmap[1]().get_map(), index)
        self.clear_vertex(vertex)
        libcore.remove_vertex(self.__graph, vertex)

    def remove_vertex_if(self, predicate):
        """Remove all the vertices from the graph for which ``predicate(v)``
        evaluates to ``True``. """
        N = self.num_vertices()
        for i in xrange(0, N):
            v = self.vertex(N - i - 1)
            if predicate(v):
                self.remove_vertex(v)

    def clear_vertex(self, vertex):
        """Remove all in and out-edges from the given vertex."""
        del_es = set()
        for e in vertex.all_edges():
            del_es.add(e)
        for e in del_es:
            self.remove_edge(e)

    def add_edge(self, source, target):
        """Add a new edge from ``source`` to ``target`` to the graph, and return
        it."""
        self.__check_perms("add_edge")
1104
        e = libcore.add_edge(weakref.ref(self), source, target)
1105
1106
1107
1108
        efilt = self.get_edge_filter()
        if efilt[0] is not None:
            efilt[0][e] = not efilt[1]
        return e
Tiago Peixoto's avatar
Tiago Peixoto committed
1109
1110
1111
1112

    def remove_edge(self, edge):
        """Remove an edge from the graph."""
        self.__check_perms("del_edge")
Tiago Peixoto's avatar
Tiago Peixoto committed
1113
        return libcore.remove_edge(self.__graph, edge)
Tiago Peixoto's avatar
Tiago Peixoto committed
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163

    def remove_edge_if(self, predicate):
        """Remove all edges from the graph, for which ``predicate(e)`` evaluates
        to ``True``."""
        for v in self.vertices():
            del_es = []
            for e in v.out_edges():
                if predicate(e):
                    del_es.append(e)
            for e in del_es:
                self.remove_edge(e)

    def clear(self):
        """Remove all vertices and edges from the graph."""
        self.__check_perms("del_vertex")
        self.__check_perms("del_edge")
        self.__graph.Clear()

    def clear_edges(self):
        """Remove all edges from the graph."""
        self.__check_perms("del_edge")
        self.__graph.ClearEdges()

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

    # all properties
    def __get_properties(self):
        return PropertyDict(self, self.__properties,
                            lambda g, k: g.__properties[k],
                            lambda g, k, v: g.__set_property(k[0], k[1], v),
                            lambda g, k: g.__del_property(k[0], k[1]))

    @_limit_args({"t": ["v", "e", "g"]})
    @_require("k", str)
    @_require("v", PropertyMap)
    def __set_property(self, t, k, v):
        if t != v.key_type():
            raise ValueError("wrong key type for property map")
        self.__properties[(t, k)] = v

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

    properties = property(__get_properties,
                          doc=
    """Dictionary of internal properties. Keys must always be a tuple, where the
    first element if a string from the set {'v', 'e', 'g'}, representing a
1164
1165
    vertex, edge or graph property, respectively, and the second element is the
    name of the property map.
Tiago Peixoto's avatar
Tiago Peixoto committed
1166
1167
1168
1169
1170
1171
1172
1173
1174

    Examples
    --------
    >>> g = gt.Graph()
    >>> g.properties[("e", "foo")] = g.new_edge_property("vector<double>")
    >>> del g.properties[("e", "foo")]
    """)

    def __get_specific_properties(self, t):
1175
1176
        props = dict([(k[1], v) for k, v in self.__properties.iteritems() \
                      if k[0] == t])
Tiago Peixoto's avatar
Tiago Peixoto committed
1177
1178
1179
1180
1181
1182
1183
1184
1185
        return props

    # vertex properties
    def __get_vertex_properties(self):
        return PropertyDict(self, self.__get_specific_properties("v"),
                            lambda g, k: g.__properties[("v", k)],
                            lambda g, k, v: g.__set_property("v", k, v),
                            lambda g, k: g.__del_property("v", k))
    vertex_properties = property(__get_vertex_properties,
1186
                                 doc="Dictionary of internal vertex properties. The keys are the property names.")
Tiago Peixoto's avatar
Tiago Peixoto committed
1187
1188
1189
1190
1191
1192
1193
1194

    # edge properties
    def __get_edge_properties(self):
        return PropertyDict(self, self.__get_specific_properties("e"),
                            lambda g, k: g.__properties[("e", k)],
                            lambda g, k, v: g.__set_property("e", k, v),
                            lambda g, k: g.__del_property("e", k))
    edge_properties = property(__get_edge_properties,
1195
                                 doc="Dictionary of internal edge properties. The keys are the property names.")
Tiago Peixoto's avatar
Tiago Peixoto committed
1196
1197
1198
1199
1200
1201
1202
1203

    # graph properties
    def __get_graph_properties(self):
        return PropertyDict(self, self.__get_specific_properties("g"),
                            lambda g, k: g.__properties[("g", k)],
                            lambda g, k, v: g.__set_property("g", k, v),
                            lambda g, k: g.__del_property("g", k))
    graph_properties = property(__get_graph_properties,
1204
                                 doc="Dictionary of internal graph properties. The keys are the property names.")
Tiago Peixoto's avatar
Tiago Peixoto committed
1205

1206
1207
1208
1209
    def own_property(self, prop):
        """'Own' property map 'prop', which may belong to another graph."""
        return PropertyMap(prop._PropertyMap__map, self, prop.key_type())

Tiago Peixoto's avatar
Tiago Peixoto committed
1210
    def list_properties(self):
1211
        """Print a list of all internal properties.
Tiago Peixoto's avatar
Tiago Peixoto committed
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249

        Examples
        --------
        >>> g = gt.Graph()
        >>> g.properties[("e", "foo")] = g.new_edge_property("vector<double>")
        >>> g.vertex_properties["foo"] = g.new_vertex_property("double")
        >>> g.vertex_properties["bar"] = g.new_vertex_property("python::object")
        >>> g.graph_properties["gnat"] = g.new_graph_property("string", "hi there!")
        >>> g.list_properties()
        gnat           (graph)   (type: string, val: hi there!)
        bar            (vertex)  (type: python::object)
        foo            (vertex)  (type: double)
        foo            (edge)    (type: vector<double>)
        """

        if len(self.__properties) == 0:
            return
        w = max([len(x[0]) for x in self.__properties.keys()]) + 4
        w = w if w > 14 else 14

        for k, v in self.__properties.iteritems():
            if k[0] == "g":
                print "%%-%ds (graph)   (type: %%s, val: %%s)" % w % \
                      (k[1], v.value_type(), str(v[self]))
        for k, v in self.__properties.iteritems():
            if k[0] == "v":
                print "%%-%ds (vertex)  (type: %%s)" % w % (k[1],
                                                            v.value_type())
        for k, v in self.__properties.iteritems():
            if k[0] == "e":
                print "%%-%ds (edge)    (type: %%s)" % w % (k[1],
                                                            v.value_type())

    # index properties

    def _get_vertex_index(self):
        return self.__vertex_index
    vertex_index = property(_get_vertex_index,
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
                            doc="""Vertex index map.

                            It maps for each vertex in the graph an unique
                            integer in the range [0, :meth:`~graph_tool.Graph.num_vertices` - 1].

                            .. note::

                                This is a special instance of a :class:`~graph_tool.PropertyMap`
                                class, which is **immutable**, and cannot be
                                accessed as an array.""")
Tiago Peixoto's avatar
Tiago Peixoto committed
1260
1261
1262

    def _get_edge_index(self):
        return self.__edge_index
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
    edge_index = property(_get_edge_index, doc="""Edge index map.

                            It maps for each edge in the graph an unique
                            integer.

                            .. warning::

                                Differently from :attr:`~graph_tool.Graph.vertex_index`,
                                this is a **regular** instance of a :class:`~graph_tool.PropertyMap`
                                class, and is therefore **mutable**!

                                Additionally, the indexes may not necessarily
                                lie in the range [0, :meth:`~graph_tool.Graph.num_edges` - 1].
                                However this will always happen whenever no
                                edges are deleted from the graph.

                                The internal consistency expected by most
                                algorithms and the proper functioning of
                                property maps assume that the indexes are unique
                                and constant, which is guaranteed by the
                                library.  Therefore it is recommended **never**
                                to modify these values, unless you know what you
                                are doing.""")
Tiago Peixoto's avatar
Tiago Peixoto committed
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301

    def _get_max_edge_index(self):
        return self.__graph.GetMaxEdgeIndex()
    max_edge_index = property(_get_max_edge_index,
                              doc="The maximum value of the edge index map.")

    def reindex_edges(self):
        """
        Reset the edge indexes so that they lie in the [0, :meth:`~graph_tool.Graph.num_edges` - 1]
        range. The index ordering will be compatible with the sequence returned
        by the :meth:`~graph_tool.Graph.edges` function.

        .. WARNING::

           Calling this function will invalidate all existing edge property
           maps, if the index ordering is modified! The property maps will still
1302
1303
           be usable, but their contents will still be tied to the old indexes,
           and thus may become scrambled.
Tiago Peixoto's avatar
Tiago Peixoto committed
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
        """
        self.__graph.ReIndexEdges()

    # Property map creation

    def new_property(self, key_type, value_type):
        """Create a new (uninitialized) vertex property map of key type
        ``key_type`` (``v``, ``e`` or ``g``), value type ``value_type``, and
        return it.
        """
        if key_type == "v" or key_type == "vertex":
            return self.new_vertex_property(value_type)
        if key_type == "e" or key_type == "edge":
            return self.new_edge_property(value_type)
        if key_type == "g" or key_type == "graph":
            return self.new_graph_property(value_type)
        raise ValueError("unknown key type: " + key_type)

    def new_vertex_property(self, value_type):
        """Create a new (uninitialized) vertex property map of type
        ``value_type``, and return it."""
        return PropertyMap(new_vertex_property(_type_alias(value_type),
                                               self.__graph.GetVertexIndex()),
                           self, "v")

    def new_edge_property(self, value_type):
        """Create a new (uninitialized) edge property map of type
        ``value_type``, and return it."""
        return PropertyMap(new_edge_property(_type_alias(value_type),
                                             self.__graph.GetEdgeIndex()),
                           self, "e")

    def new_graph_property(self, value_type, val=None):
        """Create a new graph property map of type ``value_type``, and return
        it. If ``val`` is not None, the property is initialized to its value."""
        prop = PropertyMap(new_graph_property(_type_alias(value_type),
                                              self.__graph.GetGraphIndex()),
                           self, "g", lambda k: k.__graph)
        if val != None:
            prop[self] = val
        return prop

    # property map copying
    @_require("src", PropertyMap)
    @_require("tgt", (PropertyMap, type(None)))
    def copy_property(self, src, tgt=None, value_type=None, g=None):
        """Copy contents of ``src`` property to ``tgt`` property. If ``tgt`` is
        None, then a new property map of the same type (or with the type given
        by the optional ``value_type`` parameter) is created, and returned. The
        optional parameter g specifies the (identical) source graph to copy
        properties from (defaults to self).
        """
1356
        if tgt is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
            tgt = self.new_property(src.key_type(),
                                    (src.value_type()
                                     if value_type == None else value_type))
            ret = tgt
        else:
            ret = None

        if src.key_type() != tgt.key_type():
            raise ValueError("source and target properties must have the same" +
                             " key type")
1367
        if g is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1368
            g = self
1369
1370
1371
        if g is not self:
            g.stash_filter(directed=True, reversed=True)
        self.stash_filter(directed=True, reversed=True)
Tiago Peixoto's avatar
Tiago Peixoto committed
1372
1373
        if src.key_type() == "v":
            self.__graph.CopyVertexProperty(g.__graph, _prop("v", g, src),
1374
                                            _prop("v", self, tgt))
Tiago Peixoto's avatar
Tiago Peixoto committed
1375
1376
        elif src.key_type() == "e":
            self.__graph.CopyEdgeProperty(g.__graph, _prop("e", g, src),
1377
                                            _prop("e", self, tgt))
Tiago Peixoto's avatar
Tiago Peixoto committed
1378
1379
        else:
            tgt[self] = src[g]
1380
1381
1382
        self.pop_filter(directed=True, reversed=True)
        if g is not self:
            g.pop_filter(directed=True, reversed=True)
Tiago Peixoto's avatar
Tiago Peixoto committed
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
        return ret

    # degree property map
    @_limit_args({"deg": ["in", "out", "total"]})
    def degree_property_map(self, deg):
        """Create and return a vertex property map containing the degree type
        given by ``deg``."""
        return PropertyMap(self.__graph.DegreeMap(deg), self, "v")

    # I/O operations
    # ==============
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
    def __get_file_format(self, file_name):
        fmt = None
        for f in ["xml", "dot", "gml"]:
            names = ["." + f, ".%s.gz" % f, ".%s.bz2" % f]
            for name in names:
                if file_name.endswith(name):
                    fmt = f
                    break
        if fmt is None:
            raise ValueError("cannot determine file format of: " + file_name)
        return fmt

    def load(self, file_name, fmt="auto"):
Tiago Peixoto's avatar
Tiago Peixoto committed
1407
1408
        """Load graph from ``file_name`` (which can be either a string or a
        file-like object). The format is guessed from ``file_name``, or can be
1409
        specified by ``fmt``, which can be either "xml", "dot" or "gml". """
Tiago Peixoto's avatar
Tiago Peixoto committed
1410
1411
1412

        if type(file_name) == str:
            file_name = os.path.expanduser(file_name)
1413
1414
1415
1416
        if fmt == 'auto' and isinstance(file_name, str):
            fmt = self.__get_file_format(file_name)
        elif fmt == "auto":
            fmt = "xml"
Tiago Peixoto's avatar
Tiago Peixoto committed
1417
        if isinstance(file_name, str):
1418
            props = self.__graph.ReadFromFile(file_name, None, fmt)
Tiago Peixoto's avatar
Tiago Peixoto committed
1419
        else:
1420
            props = self.__graph.ReadFromFile("", file_name, fmt)
Tiago Peixoto's avatar
Tiago Peixoto committed
1421
1422
1423
1424
1425
1426
1427
1428
        for name, prop in props[0].iteritems():
            self.vertex_properties[name] = PropertyMap(prop, self, "v")
        for name, prop in props[1].iteritems():
            self.edge_properties[name] = PropertyMap(prop, self, "e")
        for name, prop in props[2].iteritems():
            self.graph_properties[name] = PropertyMap(prop, self, "g",
                                                      lambda k: k.__graph)

1429
    def save(self, file_name, fmt="auto"):
Tiago Peixoto's avatar
Tiago Peixoto committed
1430
1431
        """Save graph to ``file_name`` (which can be either a string or a
        file-like object). The format is guessed from the ``file_name``, or can
1432
        be specified by ``fmt``, which can be either "xml", "dot" or "gml". """
Tiago Peixoto's avatar
Tiago Peixoto committed
1433
1434
1435

        if type(file_name) == str:
            file_name = os.path.expanduser(file_name)
1436
1437
1438
1439
        if fmt == 'auto' and isinstance(file_name, str):
            fmt = self.__get_file_format(file_name)
        elif fmt == "auto":
            fmt = "xml"
Tiago Peixoto's avatar
Tiago Peixoto committed
1440
1441
1442
        props = [(name[1], prop._PropertyMap__map) for name, prop in \
                 self.__properties.iteritems()]
        if isinstance(file_name, str):
1443
            self.__graph.WriteToFile(file_name, None, fmt, props)
Tiago Peixoto's avatar
Tiago Peixoto committed
1444
        else:
1445
            self.__graph.WriteToFile("", file_name, fmt, props)
Tiago Peixoto's avatar
Tiago Peixoto committed
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505

    # Directedness
    # ============

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

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

    # Reversedness
    # ============

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

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

    # Filtering
    # =========

    def set_vertex_filter(self, prop, inverted=False):
        """Choose vertex boolean filter property. Only the vertices with value
        different than zero are kept in the filtered graph. If the ``inverted``
        option is supplied with value ``True``, only the vertices with value
        zero are kept. If the supplied property is ``None``, any previous
        filtering is removed."""

        self.__graph.SetVertexFilterProperty(_prop("v", self, prop),
                                             inverted)
        self.__filter_state["vertex_filter"] = (prop, inverted)

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

    def set_edge_filter(self, prop, inverted=False):
        """Choose edge boolean filter property. Only the edges with value
        different than zero are kept in the filtered graph. If the ``inverted``
        option is supplied with value ``True``, only the edges with value zero
        are kept. If the supplied property is ``None``, any previous filtering
        is removed."""
        self.__graph.SetEdgeFilterProperty(_prop("e", self, prop), inverted)
        self.__filter_state["edge_filter"] = (prop, inverted)

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

    def purge_vertices(self):
        """Remove all vertices of the graph which are currently being filtered
1506
1507
1508
1509
        out, and return it to the unfiltered state. This operation is not
        reversible."""
        old_indexes = self.vertex_index.copy("int32_t")
        self.__graph.PurgeVertices(_prop("v", self, old_indexes))
Tiago Peixoto's avatar
Tiago Peixoto committed
1510
        self.set_vertex_filter(None)
1511
1512
1513
1514
        for pmap in self.__known_properties:
            if pmap[0] == "v" and pmap[1]() != None and pmap[1]().is_writable():
                self.__graph.ReIndexVertexProperty(pmap[1]().get_map(),
                                                   _prop("v", self, old_indexes))
Tiago Peixoto's avatar
Tiago Peixoto committed
1515
1516
1517

    def purge_edges(self):
        """Remove all edges of the graph which are currently being filtered out,
1518
        and return it to the unfiltered state. This operation is not reversible."""
Tiago Peixoto's avatar
Tiago Peixoto committed
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
        self.__graph.PurgeEdges()
        self.set_edge_filter(None)

    def stash_filter(self, edge=False, vertex=False, directed=False,
                     reversed=False, all=True):
        """Stash current filter state and set the graph to its unfiltered
        state. The optional keyword arguments specify which type of filter
        should be stashed."""
        if edge or vertex or directed or reversed:
            all = False
        self.__stashed_filter_state.append(self.get_filter_state())
        if libcore.graph_filtering_enabled():
            if vertex or all:
                self.set_vertex_filter(None)
            if edge or all:
                self.set_edge_filter(None)
        if directed or all:
            self.set_directed(True)
        if reversed or all:
            self.set_reversed(False)

    def pop_filter(self, edge=False, vertex=False, directed=False,
                   reversed=False, all=True):
        """Pop last stashed filter state. The optional keyword arguments specify
        which type of filter should be recovered."""
        if edge or vertex or directed or reversed:
            all = False
        state = self.__stashed_filter_state.pop()
        if libcore.graph_filtering_enabled():
            if vertex or all:
                self.set_vertex_filter(state["vertex_filter"][0],
                                       state["vertex_filter"][1])
            if edge or all:
                self.set_edge_filter(state["edge_filter"][0],
                                     state["edge_filter"][1])
        if directed or all:
            self.set_directed(state["directed"])
        if reversed or all:
            self.set_reversed(state["reversed"])

    def get_filter_state(self):
        """Return a copy of the filter state of the graph."""
        self.__filter_state["directed"] = self.is_directed()
        self.__filter_state["reversed"] = self.is_reversed()
        return copy.copy(self.__filter_state)

    def set_filter_state(self, state):
        """Set the filter state of the graph."""
        if libcore.graph_filtering_enabled():
            self.set_vertex_filter(state["vertex_filter"][0],
                                   state["vertex_filter"][1])
            self.set_edge_filter(state["edge_filter"][0],
                                 state["edge_filter"][1])
        self.set_directed(state["directed"])
        self.set_reversed(state["reversed"])

    # Basic graph statistics
    # ======================

    def num_vertices(self):
1579
1580
1581
1582
1583
1584
1585
        """Get the number of vertices.

        .. note::

            If the vertices are being filtered, this operation is
            :math:`O(N)`. Otherwise it is :math:`O(1)`.
        """
Tiago Peixoto's avatar
Tiago Peixoto committed
1586
1587
1588
        return self.__graph.GetNumberOfVertices()

    def num_edges(self):
1589
1590
1591
1592
1593
1594
1595
        """Get the number of edges.

        .. note::

            If the edges are being filtered, this operation is
            :math:`O(E)`. Otherwise it is :math:`O(1)`.
        """
Tiago Peixoto's avatar
Tiago Peixoto committed
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
        return self.__graph.GetNumberOfEdges()

    # Pickling support
    # ================

    def __getstate__(self):
        state = dict()
        sio = StringIO()
        if libcore.graph_filtering_enabled():
            if self.get_vertex_filter()[0] != None:
                self.vertex_properties["_Graph__pickle__vfilter"] = \
                    self.get_vertex_filter()[0]
                state["vfilter"] = self.get_vertex_filter()[1]
            if self.get_edge_filter()[0] != None:
                self.edge_properties["_Graph__pickle__efilter"] = \
                    self.get_edge_filter()[0]
                state["efilter"] = self.get_edge_filter()[1]
        self.save(sio, "xml")
        state["blob"] = sio.getvalue()
        return state

    def __setstate__(self, state):
        self.__init__()
        blob = state["blob"]
        if blob != "":
            sio = StringIO(blob)
            self.load(sio, "xml")
        if "vfilt" in state:
            vprop = self.vertex_properties["_Graph__pickle__vfilter"]
            self.set_vertex_filter(vprop, state["vfilt"])
        if "efilt" in state:
            eprop = self.edge_properties["_Graph__pickle__efilter"]
            self.set_edge_filter(eprop, state["efilt"])


1631
def load_graph(file_name, fmt="auto"):
Tiago Peixoto's avatar
Tiago Peixoto committed
1632
1633
1634
1635
    """
    Load a graph from ``file_name`` (which can be either a string or a file-like object).

    The format is guessed from ``file_name``, or can be specified by
1636
    ``fmt``, which can be either "xml", "dot" or "gml".
Tiago Peixoto's avatar
Tiago Peixoto committed
1637
1638
    """
    g = Graph()
1639
    g.load(file_name, fmt)
Tiago Peixoto's avatar
Tiago Peixoto committed
1640
1641
1642
1643
1644
1645
1646
1647
1648
    return g


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

# Vertex and Edge Types
# =====================
1649
from libgraph_tool_core import Vertex, Edge, EdgeBase
Tiago Peixoto's avatar
Tiago Peixoto committed
1650
1651
1652

Vertex.__doc__ = """Vertex descriptor.

1653
1654
1655
1656
1657
This class represents a vertex in a :class:`~graph_tool.Graph` instance.

:class:`~graph_tool.Vertex` instances are hashable, and are convertible to
integers, corresponding to its index (see :attr:`~graph_tool.Graph.vertex_index`).
"""
Tiago Peixoto's avatar
Tiago Peixoto committed
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699


def _out_neighbours(self):
    """Return an iterator over the out-neighbours."""
    for e in self.out_edges():
        yield e.target()
Vertex.out_neighbours = _out_neighbours


def _in_neighbours(self):
    """Return an iterator over the in-neighbours."""
    for e in self.in_edges():
        yield e.source()
Vertex.in_neighbours = _in_neighbours


def _all_edges(self):
    """Return an iterator over all edges (both in or out)."""
    for e in self.out_edges():
        yield e
    for e in self.in_edges():
        yield e
Vertex.all_edges = _all_edges


def _all_neighbours(self):
    """Return an iterator over all neighbours (both in or out)."""
    for v in self.out_neighbours():
        yield v
    for v in self.in_neighbours():
        yield v
Vertex.all_neighbours = _all_neighbours


def _vertex_repr(self):
    if not self.is_valid():
        return "<invalid Vertex object at 0x%x>" % (id(self))
    return "<Vertex object with index '%d' at 0x%x>" % (int(self), id(self))
Vertex.__repr__ = _vertex_repr

_edge_doc = """Edge descriptor.

1700
1701
1702
1703
1704
This class represents an edge in a :class:`~graph_tool.Graph`.

:class:`~graph_tool.Edge` instances are hashable, and are convertible to a
tuple, which contains the source and target vertices.
"""
Tiago Peixoto's avatar
Tiago Peixoto committed
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722


def _edge_iter(self):
    """Iterate over the source and target"""
    for v in [self.source(), self.target()]:
        yield v


def _edge_repr(self):
    if not self.is_valid():
        return "<invalid Edge object at 0x%x>" % (id(self))

    return ("<Edge object with source '%d' and target '%d'" +
            " at 0x%x>") % (int(self.source()), int(self.target()), id(self))


# There are several edge classes... me must cycle through them all to modify
# them.
1723

Tiago Peixoto's avatar
Tiago Peixoto committed
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
def init_edge_classes():
    for directed in [True, False]:
        for e_reversed in [True, False]:
            for e_filtered in [True, False]:
                for v_filtered in [True, False]:
                    g = Graph(directed=directed)
                    g.set_reversed(e_reversed)
                    v = g.add_vertex()
                    g.add_edge(v, v)
                    if e_filtered:
                        e_filter = g.new_edge_property("bool")
                        e_filter.a = [1]
                        g.set_edge_filter(e_filter)
                    if v_filtered:
                        v_filter = g.new_vertex_property("bool")
                        v_filter.a = [1]
                        g.set_vertex_filter(v_filter)
                    e = g.edges().next()
                    e.__class__.__repr__ = _edge_repr
                    e.__class__.__iter__ = _edge_iter
                    e.__class__.__doc__ = _edge_doc

init_edge_classes()

1748
1749
1750
1751
1752
1753
1754
1755
# some shenanigans to make it seem there is only a single edge class
EdgeBase.__doc__ = Edge.__doc__
EdgeBase.source = Edge.source
EdgeBase.target = Edge.target
EdgeBase.is_valid = Edge.is_valid
EdgeBase.get_graph = Edge.get_graph
Edge = EdgeBase
Edge.__name__ = "Edge"
Tiago Peixoto's avatar
Tiago Peixoto committed
1756
1757


1758
# Add convenience function to vector classes
Tiago Peixoto's avatar
Tiago Peixoto committed
1759
1760
1761
def _get_array_view(self):
    return self.get_array()[:]

1762
1763
1764
1765

def _set_array_view(self, v):
    self.get_array()[:] = v

Tiago Peixoto's avatar
Tiago Peixoto committed
1766
1767
1768
vector_types = [Vector_bool, Vector_int32_t, Vector_int64_t, Vector_double,
                Vector_long_double]
for vt in vector_types:
1769
    vt.a = property(_get_array_view, _set_array_view,
1770
                    doc=r"""Shortcut to the `get_array` method as an attribute.""")
1771
    vt.__repr__ = lambda self: self.a.__repr__()
Tiago Peixoto's avatar
Tiago Peixoto committed
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
Vector_string.a = None
Vector_string.get_array = lambda self: None


class GraphView(Graph):
    """
    A view of selected vertices or edges of another graph.

    This class uses shared data from another :class:`~graph_tool.Graph`
    instance, but allows for local filtering of vertices and/or edges, edge
1782
1783
    directionality or reversal. See :ref:`sec_graph_views` for more details and
    examples.
Tiago Peixoto's avatar
Tiago Peixoto committed
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814

    The existence of a :class:`~graph_tool.GraphView` object does not affect the
    original graph, except if the graph view is modified (addition or removal of
    vertices or edges), in which case the modification is directly reflected in
    the original graph (and vice-versa), since they both point to the same
    underlying data. Because of this, instances of
    :class:`~graph_tool.PropertyMap` can be used interchangeably with a graph
    and its views.

    The argument ``g`` must be an instance of a :class:`~graph_tool.Graph`
    class. If specified, ``vfilt`` and ``efilt`` select which vertices and edges
    are filtered, respectively. These parameters can either be a
    boolean-valued :class:`~graph_tool.PropertyMap` or a
    :class:`~numpy.ndarray`, which specify which vertices/edges are selected, or
    an unary function which returns ``True`` if a given vertex/edge is to be
    selected, or ``False`` otherwise.

    The boolean parameter ``directed`` can be used to set the directionality of
    the graph view. If ``directed = None``, the directionality is inherited from
    ``g``.

    If ``reversed = True``, the direction of the edges is reversed.

    If ``vfilt`` or ``efilt`` is anything other than a
    :class:`~graph_tool.PropertyMap` instance, the instantiation running time is
    :math:`O(V)` and :math:`O(E)`, respectively. Otherwise, the running time is
    :math:`O(1)`.
    """

    def __init__(self, g, vfilt=None, efilt=None, directed=None,
                 reversed=False):
1815
        self.__base = g if not isinstance(g, GraphView) else g.base
Tiago Peixoto's avatar
Tiago Peixoto committed
1816
        Graph.__init__(self)
1817
        # copy graph reference
Tiago Peixoto's avatar
Tiago Peixoto committed
1818
1819
1820
1821
        self._Graph__graph = libcore.GraphInterface(g._Graph__graph, True)
        self._Graph__properties = g._Graph__properties
        self._Graph__known_properties = g._Graph__known_properties

1822
1823
1824
1825
1826
1827
1828
1829
        # set already existent filters
        vf = g.get_vertex_filter()
        if vf[0] is not None:
            self.set_vertex_filter(vf[0], vf[1])
        ef = g.get_edge_filter()
        if ef[0] is not None:
            self.set_edge_filter(ef[0], ef[1])

Tiago Peixoto's avatar
Tiago Peixoto committed
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
        if vfilt is not None:
            if type(vfilt) is PropertyMap:
                self.set_vertex_filter(vfilt)
            else:
                vmap = self.new_vertex_property("bool")
                if issubclass(type(vfilt), numpy.ndarray):
                    vmap.a = vfilt
                else:
                    omap, inv = g.get_vertex_filter()
                    if omap is not None:
                        vmap.a = omap.a if not inv else omap.a ^ 1
                    for v in g.vertices():
                        vmap[v] = vfilt(v)
                self.set_vertex_filter(vmap)

        if efilt is not None:
            if type(efilt) is PropertyMap:
                self.set_edge_filter(efilt)
            else:
                emap = self.new_edge_property("bool")
                if issubclass(type(efilt), numpy.ndarray):
                    vmap.a = efilt
                else:
                    omap, inv = g.get_edge_filter()
                    if omap is not None:
                        emap.a = omap.a if not inv else omap.a ^ 1
                    for e in g.edges():
                        emap[e] = efilt(e)
                self.set_edge_filter(emap)

        if directed is not None:
            self.set_directed(directed)
        if reversed:
            self.set_reversed(not g.is_reversed())

1865
1866
1867
    def __get_base(self):
        return self.__base
    base = property(__get_base, doc="Base graph.")
For faster browsing, not all history is shown. View entire blame