graph_python_interface.hh 15.2 KB
Newer Older
1
2
// graph-tool -- a general graph modification and manipulation thingy
//
Tiago Peixoto's avatar
Tiago Peixoto committed
3
// Copyright (C) 2007-2011 Tiago de Paula Peixoto <tiago@skewed.de>
4
5
6
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
Tiago Peixoto's avatar
Tiago Peixoto committed
7
// as published by the Free Software Foundation; either version 3
8
9
10
11
12
13
14
15
// 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
16
// along with this program. If not, see <http://www.gnu.org/licenses/>.
17

18
19
#ifndef PYTHON_INTERFACE_HH
#define PYTHON_INTERFACE_HH
20
21
22

#include <boost/graph/graph_traits.hpp>
#include <boost/mpl/logical.hpp>
23
#include <boost/functional/hash.hpp>
24
#include <boost/iterator/iterator_facade.hpp>
25

26
27
#include "graph.hh"
#include "graph_filtering.hh"
28
#include "graph_selectors.hh"
29
#include "numpy_bind.hh"
30

31
#include <boost/python.hpp>
32
#include <boost/python/type_id.hpp>
33

34
// this file includes a simple python interface for the internally kept
35
36
37
38
// graph. It defines a PythonVertex, PythonEdge and PythonIterator template
// classes, which contain the proper member functions for graph traversal. These
// types are then specialized for each version of the adapted graph (directed,
// undirected, filtered, reversed).
39

40
41
42
43
namespace graph_tool
{
using namespace boost;

44
45
// generic iterator adaptor which can be used to iterate vertices, edges,
// out_edges and in_edges through python
46
template <class Descriptor, class Iterator>
47
class PythonIterator
48
{
49
public:
50
51
    PythonIterator(const python::object& g, std::pair<Iterator,Iterator> e)
        : _g(g), _e(e) {}
52
    Descriptor Next()
53
    {
54
55
        if (_e.first == _e.second)
            python::objects::stop_iteration_error();
56
57
58
59
        if (_g() == python::object())
            throw GraphException("The corresponding graph object has been"
                                 " deleted during iteration!");
        Descriptor e(_g, *_e.first);
60
61
        ++_e.first;
        return e;
62
63
    }
private:
64
    python::object _g;
65
    std::pair<Iterator,Iterator> _e;
Tiago Peixoto's avatar
Tiago Peixoto committed
66
67
68
};


69
// forward declaration of PythonEdge
70
71
template <class Graph>
class PythonEdge;
72

73
// below are classes related to the PythonVertex type
74
class PythonVertex
75
76
{
public:
77
78
    PythonVertex(const python::object& g, GraphInterface::vertex_t v):
        _g(g), _v(v), _valid(true)
79
80
81
82
83
84
    {
        CheckValid();
    }

    bool IsValid() const
    {
85
86
        if (_g().ptr() == Py_None)
            return false;
87
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
88
89
        return _valid &&
            (_v != graph_traits<GraphInterface::multigraph_t>::null_vertex()) &&
Tiago Peixoto's avatar
Tiago Peixoto committed
90
            (_v < num_vertices(gi._state->_mg));
91
    }
92

93
    void SetValid(bool valid)
94
    {
95
96
        _valid = valid;
    }
97

98
99
100
    void CheckValid() const
    {
        if (!IsValid())
101
102
            throw ValueException("invalid vertex descriptor: " +
                                 lexical_cast<string>(_v));
103
    }
104

105
106
107
108
109
    python::object GetGraph() const
    {
        return _g();
    }

110
    GraphInterface::vertex_t GetDescriptor() const
111
112
113
114
    {
        return _v;
    }

115
116
117
118
    template <class DegSelector>
    struct get_degree
    {
        template<class Graph>
119
        void operator()(const Graph& g,
120
121
122
                        typename graph_traits<Graph>::vertex_descriptor v,
                        size_t& deg) const
        {
123
            deg = DegSelector()(v, g);
124
125
126
        }
    };

127
    size_t GetInDegree() const
128
    {
129
        CheckValid();
130
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
131
        size_t in_deg;
132
133
134
        run_action<>()(gi, bind<void>(get_degree<in_degreeS>(),
                                      _1, _v,
                                      ref(in_deg)))();
135
        return in_deg;
136
    }
137

138
    size_t GetOutDegree() const
139
    {
140
        CheckValid();
141
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
142
        size_t out_deg;
143
144
        run_action<>()(gi, bind<void>(get_degree<out_degreeS>(), _1, _v,
                                      ref(out_deg)))();
145
        return out_deg;
Tiago Peixoto's avatar
Tiago Peixoto committed
146
147
    }

148
    // provide iterator support for out_edges
149

150
151
152
    struct get_out_edges
    {
        template<class Graph>
153
        void operator()(const Graph& g, const python::object& pg,
154
155
156
157
158
159
160
                        typename graph_traits<Graph>::vertex_descriptor v,
                        python::object& iter) const
        {
            typedef typename graph_traits<Graph>::out_edge_iterator
                out_edge_iterator;
            iter = python::object(PythonIterator<PythonEdge<Graph>,
                                                 out_edge_iterator>
161
                                  (pg, out_edges(v, g)));
162
163
164
165
        }
    };

    python::object
166
    OutEdges() const
Tiago Peixoto's avatar
Tiago Peixoto committed
167
    {
168
        CheckValid();
169
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
170
        python::object iter;
171
172
        run_action<>()(gi, bind<void>(get_out_edges(), _1,
                                      ref(_g), _v, ref(iter)))();
173
        return iter;
174
    }
175

176
177
178
    struct get_in_edges
    {
        template<class Graph>
179
        void operator()(const Graph& g, const python::object& pg,
180
181
182
183
184
185
186
                        typename graph_traits<Graph>::vertex_descriptor v,
                        python::object& iter) const
        {
            typedef typename in_edge_iteratorS<Graph>::type
                in_edge_iterator;
            iter = python::object
                (PythonIterator<PythonEdge<Graph>,in_edge_iterator>
187
                 (pg, in_edge_iteratorS<Graph>::get_edges(v, g)));
188
189
190
191
        }
    };

    python::object
192
    InEdges() const
193
    {
194
        CheckValid();
195
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
196
        python::object iter;
197
198
        run_action<>()(gi, bind<void>(get_in_edges(), _1, ref(_g), _v,
                                      ref(iter)))();
199
        return iter;
Tiago Peixoto's avatar
Tiago Peixoto committed
200
    }
201

202
203
    std::string GetString() const
    {
204
        CheckValid();
205
206
207
        return lexical_cast<std::string>(_v);
    }

208
    size_t GetHash() const
209
    {
210
        return hash<size_t>()(_v);
211
212
    }

213
214
    size_t GetIndex() const
    {
215
        CheckValid();
216
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
217
        return gi._vertex_index[_v];
218
219
    }

220
    bool operator==(const PythonVertex& other) const
221
    {
222
223
        CheckValid();
        other.CheckValid();
224
        return other._v == _v;
225
    }
226

227
    bool operator!=(const PythonVertex& other) const
228
    {
229
230
        CheckValid();
        other.CheckValid();
231
        return other._v != _v;
232
233
    }

234
private:
235
    python::object _g;
236
    GraphInterface::vertex_t _v;
237
    bool _valid;
238
};
239

240
// below are classes related to the PythonEdge type
241

242
243
class EdgeBase {}; // useful to unite all edge types

244
template <class Graph>
245
class PythonEdge : public EdgeBase
246
247
{
public:
Tiago Peixoto's avatar
Tiago Peixoto committed
248
    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;
249
250
    PythonEdge(const python::object& g, edge_descriptor e)
        : _g(g), _e(e), _valid(true)
251
252
253
254
255
    {
        CheckValid();
    }

    bool IsValid() const
Tiago Peixoto's avatar
Tiago Peixoto committed
256
    {
257
258
        if (_g().ptr() == Py_None)
            return false;
259
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
260
        GraphInterface::edge_t e(_e);
Tiago Peixoto's avatar
Tiago Peixoto committed
261
262
263
        return (_valid &&
                PythonVertex(_g, source(e, gi._state->_mg)).IsValid() &&
                PythonVertex(_g, target(e, gi._state->_mg)).IsValid());
264
265
266
267
268
269
270
271
272
    }

    void SetValid(bool valid)
    {
        _valid = valid;
    }

    void CheckValid() const
    {
273
        if (!IsValid())
Tiago Peixoto's avatar
Tiago Peixoto committed
274
            throw ValueException("invalid edge descriptor");
Tiago Peixoto's avatar
Tiago Peixoto committed
275
276
    }

277
278
279
280
281
    python::object GetGraph() const
    {
        return _g();
    }

282
    GraphInterface::edge_t GetDescriptor() const
283
284
285
286
    {
        return _e;
    }

287
288
289
    struct get_source
    {
        template<class GraphType>
290
        void operator()(const GraphType& g, const python::object& pg,
291
292
293
                        const edge_descriptor& edge, python::object& vertex)
            const
        {
294
295
            typedef typename graph_traits<GraphType>::edge_descriptor edge_t;
            vertex = python::object(PythonVertex(pg, source(edge_t(edge), g)));
296
297
        }
    };
298

299
    python::object GetSource() const
Tiago Peixoto's avatar
Tiago Peixoto committed
300
    {
301
        CheckValid();
302
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
303
        python::object v;
304
305
        run_action<>()(gi, bind<void>(get_source(), _1, ref(_g), ref(_e),
                                      ref(v)))();
306
        return v;
Tiago Peixoto's avatar
Tiago Peixoto committed
307
308
    }

309
310
311
    struct get_target
    {
        template<class GraphType>
312
313
314
        void operator()(const GraphType& g, const python::object& pg,
                        const edge_descriptor& edge, python::object& vertex)
            const
315
        {
316
317
            typedef typename graph_traits<GraphType>::edge_descriptor edge_t;
            vertex = python::object(PythonVertex(pg, target(edge_t(edge), g)));
318
319
        }
    };
320

321
    python::object GetTarget() const
Tiago Peixoto's avatar
Tiago Peixoto committed
322
    {
323
        CheckValid();
324
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
325
        python::object v;
326
327
        run_action<>()(gi, bind<void>(get_target(), _1, ref(_g), ref(_e),
                                      ref(v)))();
328
        return v;
Tiago Peixoto's avatar
Tiago Peixoto committed
329
330
    }

331
332
    std::string GetString() const
    {
333
334
        PythonVertex src = python::extract<PythonVertex>(GetSource());
        PythonVertex tgt = python::extract<PythonVertex>(GetTarget());
335
        return "(" + src.GetString() + ", " + tgt.GetString() + ")";
336
337
    }

338
    size_t GetHash() const
Tiago Peixoto's avatar
Tiago Peixoto committed
339
    {
340
        CheckValid();
341
        GraphInterface& gi = python::extract<GraphInterface&>(_g().attr("_Graph__graph"));
342
        return hash<size_t>()(gi._edge_index[_e]);
Tiago Peixoto's avatar
Tiago Peixoto committed
343
344
    }

345
    bool operator==(const PythonEdge& other) const
Tiago Peixoto's avatar
Tiago Peixoto committed
346
    {
347
        CheckValid();
348
        other.CheckValid();
349
        return other._e == _e;
Tiago Peixoto's avatar
Tiago Peixoto committed
350
    }
351

352
    bool operator!=(const PythonEdge& other) const
353
    {
354
        CheckValid();
355
        other.CheckValid();
356
        return other._e != _e;
357
358
359
    }

private:
360
    python::object _g;
361
    edge_descriptor _e;
362
    bool _valid;
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
// metafunction to determine wether or not to return copies or internal
// references to property types
struct return_reference
{
    template <class ValueType>
    struct apply
    {
        // return actual references only for non-string and non-python::object
        // classes

        typedef typename mpl::if_<
            typename mpl::and_<
                is_class<ValueType>,
                typename mpl::and_<
                    typename mpl::not_<is_same<ValueType,
                                               string> >::type,
                    typename mpl::not_<is_same<ValueType,
                                               python::object> >::type>::type
                >::type,
            mpl::bool_<true>,
            mpl::bool_<false> >::type type;
    };
};

template <class PropertyMap>
390
391
392
class PythonPropertyMap
{
public:
393
394
    PythonPropertyMap(const PropertyMap& pmap)
        : _pmap(pmap) {}
395

396
397
398
399
400
401
402
    typedef typename property_traits<PropertyMap>::value_type value_type;

    typedef typename mpl::if_<
        typename return_reference::apply<value_type>::type,
        value_type&,
        value_type>::type reference;

403
    template <class PythonDescriptor>
404
    reference GetValue(const PythonDescriptor& key)
405
    {
406
        key.CheckValid();
407
        return get(_pmap, key.GetDescriptor());
408
409
    }

410
411
    // in this case, val should be a copy, not a reference. This is to avoid a
    // problem with vector-valued property maps
412
    template <class PythonDescriptor>
413
    void SetValue(const PythonDescriptor& key, value_type val)
414
    {
415
416
417
418
        set_value(key, val,
                  is_convertible<
                  typename property_traits<PropertyMap>::category,
                  writable_property_map_tag>());
419
420
    }

421
422
423
    template <class PythonDescriptor>
    void set_value(const PythonDescriptor& key, const value_type& val,
                   true_type)
424
    {
425
426
        key.CheckValid();
        put(_pmap, key.GetDescriptor(), val);
427
428
    }

429
    template <class PythonDescriptor>
430
431
    void set_value(const PythonDescriptor& key, const value_type& val,
                   false_type)
432
    {
Tiago Peixoto's avatar
Tiago Peixoto committed
433
        throw ValueException("property is read-only");
434
435
436
437
    }

    size_t GetHash() const
    {
438
        return hash<size_t>()(size_t(this));
439
440
441
442
    }

    std::string GetType() const
    {
443
444
445
446
447
448
449
        using python::detail::gcc_demangle;
        if (is_same<typename mpl::find<value_types,value_type>::type,
                    typename mpl::end<value_types>::type>::value)
            return gcc_demangle(typeid(value_type).name());
        else
            return type_names[mpl::find<value_types,
                                        value_type>::type::pos::value];
450
451
    }

452
    boost::any GetMap() const
453
454
455
456
    {
        return _pmap;
    }

457
458
459
460
461
462
463
    boost::any GetDynamicMap() const
    {
        return (dynamic_property_map*)
            (new boost::detail::dynamic_property_map_adaptor<PropertyMap>
             (_pmap));
    }

464
465
466
    python::object GetArray(size_t size)
    {
        typedef typename mpl::or_<
467
468
469
470
471
472
473
474
475
              typename mpl::or_<
                   is_same<PropertyMap,
                           GraphInterface::vertex_index_map_t>,
                   is_same<PropertyMap,
                           GraphInterface::edge_index_map_t> >::type,
              typename mpl::not_<
                  typename mpl::has_key<numpy_types, value_type>::type >
            ::type>::type isnt_vector_map;
        return get_array(_pmap, size, isnt_vector_map());
476
477
478
479
480
481
482
483
484
485
486
487
488
    }

    python::object get_array(PropertyMap pmap, size_t size, mpl::bool_<false>)
    {
        _pmap.reserve(size);
        return wrap_vector_not_owned(_pmap.get_storage());
    }

    python::object get_array(PropertyMap pmap, size_t size, mpl::bool_<true>)
    {
        return python::object();
    }

489
490
    bool IsWritable() const
    {
491
492
        return is_convertible<typename property_traits<PropertyMap>::category,
                              writable_property_map_tag>::value;
493
494
    }

495
private:
496
    PropertyMap _pmap; // hold an internal copy, since it's cheap
497
498
499
};


500
501
502
503
504
505
506
507
508
509
510
511
512
//
// Create new properties
//

struct new_property_map
{
    template <class ValueType, class IndexMap>
    void operator()(ValueType, IndexMap index, const string& type_name,
                    python::object& new_prop, bool& found) const
    {
        size_t i = mpl::find<value_types,ValueType>::type::pos::value;
        if (type_name == type_names[i])
        {
513
514
            typedef typename property_map_type::apply<ValueType, IndexMap>::type
                map_t;
515
516
517
518
519
520
521
522
            map_t prop(index);
            new_prop = python::object(PythonPropertyMap<map_t>(prop));
            found = true;
        }
    }
};

template <class IndexMap>
523
python::object new_property(const string& type, IndexMap index_map)
524
525
526
{
    python::object prop;
    bool found = false;
527
528
    mpl::for_each<value_types>(bind<void>(new_property_map(), _1, index_map,
                                          ref(type), ref(prop), ref(found)));
529
    if (!found)
Tiago Peixoto's avatar
Tiago Peixoto committed
530
        throw ValueException("Invalid property type: " + type);
531
532
533
    return prop;
}

534
535
536
} //graph_tool namespace

#endif