graph_python_interface_imp1.cc 12.3 KB
Newer Older
1
2
// graph-tool -- a general graph modification and manipulation thingy
//
Tiago Peixoto's avatar
Tiago Peixoto committed
3
// Copyright (C) 2006-2020 Tiago de Paula Peixoto <tiago@skewed.de>
4
//
5
6
7
8
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option) any
// later version.
9
//
10
11
12
13
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
// details.
14
//
15
// You should have received a copy of the GNU Lesser General Public License
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include "graph_filtering.hh"
#include "graph.hh"
#include "graph_util.hh"
#include "graph_python_interface.hh"

#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include <set>


using namespace std;
using namespace boost;
using namespace graph_tool;

namespace graph_tool
{

template <class ValueList>
struct add_edge_list
{
    template <class Graph>
    void operator()(Graph& g, python::object aedge_list,
                    python::object& eprops, bool& found) const
    {
42
43
44
45
46
47
48
        boost::mpl::for_each<ValueList>(
            [&](auto&& graph)
            {
                return dispatch()
                    (g, aedge_list, eprops, found,
                     std::forward<decltype(graph)>(graph));
            });
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    }

    struct dispatch
    {
        template <class Graph, class Value>
        void operator()(Graph& g, python::object& aedge_list,
                        python::object& oeprops, bool& found, Value) const
        {
            if (found)
                return;
            try
            {
                boost::multi_array_ref<Value, 2> edge_list = get_array<Value, 2>(aedge_list);

                if (edge_list.shape()[1] < 2)
                    throw GraphException("Second dimension in edge list must be of size (at least) two");

                typedef typename graph_traits<Graph>::edge_descriptor edge_t;
                vector<DynamicPropertyMapWrap<Value, edge_t>> eprops;
                python::stl_input_iterator<boost::any> iter(oeprops), end;
                for (; iter != end; ++iter)
                    eprops.emplace_back(*iter, writable_edge_properties());

                size_t n_props = std::min(eprops.size(), edge_list.shape()[1] - 2);

                for (const auto& e : edge_list)
                {
                    size_t s = e[0];
                    size_t t = e[1];
                    while (s >= num_vertices(g) || t >= num_vertices(g))
                        add_vertex(g);
                    auto ne = add_edge(vertex(s, g), vertex(t, g), g).first;
                    for (size_t i = 0; i < n_props; ++i)
                    {
                        try
                        {
                            put(eprops[i], ne, e[i + 2]);
                        }
                        catch(bad_lexical_cast&)
                        {
                            throw ValueException("Invalid edge property value: " +
                                                 lexical_cast<string>(e[i + 2]));
                        }
                    }
                }
                found = true;
            }
96
            catch (InvalidNumpyConversion& e) {}
97
98
99
100
101
102
103
104
105
106
107
        }
    };
};

void do_add_edge_list(GraphInterface& gi, python::object aedge_list,
                      python::object eprops)
{
    typedef mpl::vector<bool, char, uint8_t, uint16_t, uint32_t, uint64_t,
                        int8_t, int16_t, int32_t, int64_t, uint64_t, double,
                        long double> vals_t;
    bool found = false;
108
109
110
111
112
113
114
115
    run_action<>()
        (gi,
         [&](auto&& graph)
         {
             return add_edge_list<vals_t>()(
                 std::forward<decltype(graph)>(graph), aedge_list, eprops,
                 found);
         })();
116
117
118
119
    if (!found)
        throw GraphException("Invalid type for edge list; must be two-dimensional with a scalar type");
}

120
121

struct add_edge_list_iter
122
{
123
124
125
    template <class Graph>
    void operator()(Graph& g, python::object& edge_list,
                    python::object& oeprops) const
126
    {
127
128
129
130
131
        typedef typename graph_traits<Graph>::edge_descriptor edge_t;
        vector<DynamicPropertyMapWrap<python::object, edge_t>> eprops;
        python::stl_input_iterator<boost::any> piter(oeprops), pend;
        for (; piter != pend; ++piter)
            eprops.emplace_back(*piter, writable_edge_properties());
132

133
134
        python::stl_input_iterator<python::object> iter(edge_list), end;
        for (; iter != end; ++iter)
135
        {
136
137
            const auto& row = *iter;
            python::stl_input_iterator<python::object> eiter(row), eend;
138

139
140
            size_t s = 0;
            size_t t = 0;
141

142
143
144
145
146
147
148
149
            typename graph_traits<Graph>::edge_descriptor e;
            size_t i = 0;
            for(; eiter != eend; ++eiter)
            {
                if (i >= eprops.size() + 2)
                    break;
                const auto& val = *eiter;
                switch (i)
150
                {
151
152
153
154
155
156
157
158
159
160
161
162
163
                case 0:
                    s = python::extract<size_t>(val);
                    while (s >= num_vertices(g))
                        add_vertex(g);
                    break;
                case 1:
                    t = python::extract<size_t>(val);
                    while (t >= num_vertices(g))
                        add_vertex(g);
                    e = add_edge(vertex(s, g), vertex(t, g), g).first;
                    break;
                default:
                    try
164
                    {
165
166
167
168
169
170
                        put(eprops[i - 2], e, val);
                    }
                    catch(bad_lexical_cast&)
                    {
                        throw ValueException("Invalid edge property value: " +
                                             python::extract<string>(python::str(val))());
171
172
                    }
                }
173
                i++;
174
175
            }
        }
176
177
    }
};
178

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
void do_add_edge_list_iter(GraphInterface& gi, python::object edge_list,
                           python::object eprops)
{
    run_action<>()
        (gi,
         [&](auto&& graph)
         {
             return add_edge_list_iter()
                 (std::forward<decltype(graph)>(graph), edge_list, eprops);
         })();
}

struct add_edge_list_hash
{
    template <class Graph, class VProp>
    void operator()(Graph& g, python::object aedge_list, VProp vmap,
                    python::object& eprops) const
    {
        typedef typename property_traits<VProp>::value_type val_t;
        if constexpr (is_scalar_v<val_t>)
199
200
201
        {
            try
            {
202
203
204
205
206
207
208
209
210
211
212
213
                numpy_dispatch(g, aedge_list, vmap, eprops);
            }
            catch (InvalidNumpyConversion&)
            {
                dispatch(g, aedge_list, vmap, eprops);
            }
        }
        else
        {
            dispatch(g, aedge_list, vmap, eprops);
        }
    }
214

215
216
217
218
219
    template <class Graph, class VProp>
    void numpy_dispatch(Graph& g, python::object& aedge_list, VProp& vmap,
                        python::object& oeprops) const
    {
        typedef typename property_traits<VProp>::value_type val_t;
220

221
222
223
224
225
        boost::multi_array_ref<val_t, 2> edge_list = get_array<val_t, 2>(aedge_list);
        typedef typename std::conditional_t<std::is_integral_v<val_t>,
                                            gt_hash_map<val_t, size_t>,
                                            unordered_map<val_t, size_t>> vmap_t;
        vmap_t vertices;
226

227
228
        if (edge_list.shape()[1] < 2)
            throw GraphException("Second dimension in edge list must be of size (at least) two");
229

230
231
232
233
234
        typedef typename graph_traits<Graph>::edge_descriptor edge_t;
        vector<DynamicPropertyMapWrap<val_t, edge_t>> eprops;
        python::stl_input_iterator<boost::any> iter(oeprops), end;
        for (; iter != end; ++iter)
            eprops.emplace_back(*iter, writable_edge_properties());
235

236
        size_t n_props = std::min(eprops.size(), edge_list.shape()[1] - 2);
237

238
239
240
241
242
243
244
245
246
        auto get_vertex = [&] (const val_t& r) -> size_t
            {
                auto iter = vertices.find(r);
                if (iter == vertices.end())
                {
                    auto v = add_vertex(g);
                    vertices[r] = v;
                    vmap[v] = r;
                    return v;
247
                }
248
249
                return iter->second;
            };
250

251
        for (const auto& e : edge_list)
252
        {
253
254
255
256
            size_t s = get_vertex(e[0]);
            size_t t = get_vertex(e[1]);
            auto ne = add_edge(vertex(s, g), vertex(t, g), g).first;
            for (size_t i = 0; i < n_props; ++i)
257
            {
258
                try
259
                {
260
261
262
263
264
265
                    put(eprops[i], ne, e[i + 2]);
                }
                catch(bad_lexical_cast&)
                {
                    throw ValueException("Invalid edge property value: " +
                                         lexical_cast<string>(e[i + 2]));
266
267
268
                }
            }
        }
269
    }
270

271
272
273
274
275
    template <class Graph, class VProp>
    void dispatch(Graph& g, python::object& edge_list, VProp& vmap,
                  python::object& oeprops) const
    {
        typedef typename property_traits<VProp>::value_type val_t;
276

277
278
279
280
        typedef typename std::conditional_t<std::is_integral_v<val_t>,
                                            gt_hash_map<val_t, size_t>,
                                            unordered_map<val_t, size_t>> vmap_t;
        vmap_t vertices;
281
282
283
284
285
286
287

        typedef typename graph_traits<Graph>::edge_descriptor edge_t;
        vector<DynamicPropertyMapWrap<python::object, edge_t>> eprops;
        python::stl_input_iterator<boost::any> piter(oeprops), pend;
        for (; piter != pend; ++piter)
            eprops.emplace_back(*piter, writable_edge_properties());

288
289
290
291
292
293
294
295
296
297
298
299
300
        auto get_vertex = [&] (const val_t& r) -> size_t
            {
                auto iter = vertices.find(r);
                if (iter == vertices.end())
                {
                    auto v = add_vertex(g);
                    vertices[r] = v;
                    vmap[v] = r;
                    return v;
                }
                return iter->second;
            };

301
302
303
304
        python::stl_input_iterator<python::object> iter(edge_list), end;
        for (; iter != end; ++iter)
        {
            const auto& row = *iter;
305

306
307
308
309
310
311
312
313
314
315
            python::stl_input_iterator<python::object> eiter(row), eend;

            size_t s = 0;
            typename graph_traits<Graph>::edge_descriptor e;
            size_t i = 0;
            for(; eiter != eend; ++eiter)
            {
                if (i >= eprops.size() + 2)
                    break;
                const auto& val = *eiter;
316
                if (i < 2)
317
                {
318
319
320
321
322
323
324
                    val_t x;
                    if constexpr (std::is_same_v<val_t, python::object>)
                        x = val;
                    else
                        x = python::extract<val_t>(val);
                    auto v = get_vertex(x);
                    while (v >= num_vertices(g))
325
                        add_vertex(g);
326
327
328
329
330
331
332
                    if (i == 0)
                        s = v;
                    else
                        e = add_edge(s, v, g).first;
                }
                else
                {
333
334
335
336
337
338
339
340
341
342
343
344
345
                    try
                    {
                        put(eprops[i - 2], e, val);
                    }
                    catch(bad_lexical_cast&)
                    {
                        throw ValueException("Invalid edge property value: " +
                                             python::extract<string>(python::str(val))());
                    }
                }
                i++;
            }
        }
346
    };
347
348
};

349
350
351
void do_add_edge_list_hashed(GraphInterface& gi, python::object aedge_list,
                             boost::any& vertex_map,
                             python::object eprops)
352
{
353
    run_action<graph_tool::all_graph_views, boost::mpl::true_>()
354
        (gi,
355
         [&](auto&& graph, auto&& a2)
356
         {
357
358
359
360
361
             return add_edge_list_hash()
                 (std::forward<decltype(graph)>(graph), aedge_list,
                  std::forward<decltype(a2)>(a2), eprops);
         },
         writable_vertex_properties())(vertex_map);
362
363
364
}

} // namespace graph_tool