graph_io.cc 18.1 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1 2
// graph-tool -- a general graph modification and manipulation thingy
//
Tiago Peixoto's avatar
Tiago Peixoto committed
3
// Copyright (C) 2006-2013 Tiago de Paula Peixoto <tiago@skewed.de>
Tiago Peixoto's avatar
Tiago Peixoto committed
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
Tiago Peixoto's avatar
Tiago Peixoto committed
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 17
// along with this program. If not, see <http://www.gnu.org/licenses/>.

18 19
#include <boost/python/extract.hpp>

20
#include <iostream>
21
#include <boost/iostreams/categories.hpp>
22 23 24
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
25
#include <boost/iostreams/device/file_descriptor.hpp>
26
#include <boost/iostreams/device/file.hpp>
27
#include <boost/graph/graphml.hpp>
28
#include <boost/graph/graphviz.hpp>
29
#include <boost/lexical_cast.hpp>
Tiago Peixoto's avatar
Tiago Peixoto committed
30
#include <boost/xpressive/xpressive.hpp>
Tiago Peixoto's avatar
Tiago Peixoto committed
31

32 33 34 35 36 37
#include "gml.hh"
#include "graph.hh"
#include "graph_filtering.hh"
#include "graph_properties.hh"
#include "graph_util.hh"

38
#include "graph_python_interface.hh"
Tiago Peixoto's avatar
Tiago Peixoto committed
39
#include "str_repr.hh"
40

Tiago Peixoto's avatar
Tiago Peixoto committed
41 42 43 44
using namespace std;
using namespace boost;
using namespace graph_tool;

45
// use correct smart pointer type for dynamic properties
46
#if (BOOST_VERSION / 100 % 1000 >= 44)
47 48 49 50 51
    #define DP_SMART_PTR boost::shared_ptr
#else
    #define DP_SMART_PTR std::auto_ptr
#endif

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
//
// Persistent IO of python::object types. All the magic is done in python,
// through the object_pickler and object_unplickler below
//

namespace graph_tool
{
python::object object_pickler;
python::object object_unpickler;
}

namespace boost
{
template <>
string lexical_cast<string,python::object>(const python::object & o)
{
    stringstream s;
    object_pickler(OStream(s), o);
    return s.str();
}

template <>
python::object lexical_cast<python::object,string>(const string& ps)
{
    stringstream s(ps);
    python::object o;
    o = object_unpickler(IStream(s));
    return o;
}
}

// the following source & sink provide iostream access to python file-like
// objects

class python_file_device
{
public:
    typedef char                 char_type;
    typedef iostreams::seekable_device_tag  category;

    python_file_device(python::object file): _file(file) {}
    std::streamsize read(char* s, std::streamsize n)
    {
        python::object pbuf = _file.attr("read")(n);
96
#if (PY_MAJOR_VERSION >= 3)
97
        string buf = python::extract<string>(pbuf.attr("decode")("utf-8"));
98 99 100
#else
        string buf = python::extract<string>(pbuf);
#endif
101 102 103 104 105 106 107 108 109
        for (size_t i = 0; i < buf.size(); ++i)
            s[i] = buf[i];
        return buf.size();
    }

    std::streamsize write(const char* s, std::streamsize n)
    {
        string buf(s, s+n);
        python::object pbuf(buf);
110
        _file.attr("write")(pbuf.attr("encode")("utf-8"));
111 112 113 114 115 116 117 118 119 120 121 122 123
        return n;
    }

    iostreams::stream_offset seek(iostreams::stream_offset off,
                                  std::ios_base::seekdir way)
    {
        _file.attr("seek")(off, int(way));
        return python::extract<iostreams::stream_offset>(_file.attr("tell")());
    }

private:
    python::object _file;
};
124

125 126 127 128 129 130
// Property Maps
// =============

struct get_python_property
{
    template <class ValueType, class IndexMap>
131
    void operator()(ValueType, IndexMap, dynamic_property_map& map,
132 133
                    python::object& pmap) const
    {
134 135
        typedef typename property_map_type::apply<ValueType, IndexMap>::type
            map_t;
136 137 138 139 140
        try
        {
            pmap = python::object
                (PythonPropertyMap<map_t>
                 (dynamic_cast
141
                  <boost::detail::dynamic_property_map_adaptor<map_t>&>(map)
142 143 144 145 146 147
                  .base()));
        } catch (bad_cast&) {}
    }
};

template <class IndexMap>
148
python::object find_property_map(dynamic_property_map& map, IndexMap)
149 150
{
    python::object pmap;
151 152 153
    mpl::for_each<value_types>(boost::bind<void>(get_python_property(),
                                                 _1, IndexMap(), ref(map),
                                                 boost::ref(pmap)));
154 155 156
    return pmap;
}

157
// this functor will check whether a value is of a specific type, create a
Tiago Peixoto's avatar
Tiago Peixoto committed
158
// corresponding vector_property_map and add the value to it
159

Tiago Peixoto's avatar
Tiago Peixoto committed
160 161 162 163
template <class IndexMap>
struct check_value_type
{
    typedef typename IndexMap::key_type key_t;
164 165
    check_value_type(IndexMap index_map, const key_t& key,
                     const boost::any& value, dynamic_property_map*& map)
166
        :_index_map(index_map), _key(key), _value(value), _map(map) {}
Tiago Peixoto's avatar
Tiago Peixoto committed
167 168 169 170

    template <class ValueType>
    void operator()(ValueType)
    {
171 172
        try
        {
173 174 175
            typedef typename property_map_type::apply<ValueType, IndexMap>::type
                map_t;
            map_t vector_map(_index_map);
176
            vector_map[_key] = any_cast<ValueType>(_value);
177 178
            _map = new boost::detail::dynamic_property_map_adaptor<map_t>
                (vector_map);
179 180
        }
        catch (bad_any_cast) {}
Tiago Peixoto's avatar
Tiago Peixoto committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    }
    IndexMap _index_map;
    const key_t& _key;
    const boost::any& _value;
    dynamic_property_map*& _map;
};

// this functor will check wether a key is a vertex or edge descriptor, and
// generate the corresponding property map, depending on the value type

template <class VertexIndexMap, class EdgeIndexMap>
struct create_dynamic_map
{
    typedef typename VertexIndexMap::key_type vertex_t;
    typedef typename EdgeIndexMap::key_type edge_t;

197 198
    create_dynamic_map(VertexIndexMap vertex_map, EdgeIndexMap edge_map)
        :_vertex_map(vertex_map), _edge_map(edge_map) {}
199
    DP_SMART_PTR<dynamic_property_map> operator()(const string&,
200 201
                                                  const boost::any& key,
                                                  const boost::any& value)
Tiago Peixoto's avatar
Tiago Peixoto committed
202
    {
203 204 205
        dynamic_property_map* map;
        try
        {
206 207 208 209
            mpl::for_each<value_types>
                (check_value_type<VertexIndexMap>(_vertex_map,
                                                  any_cast<vertex_t>(key),
                                                  value, map));
210 211 212
        }
        catch (bad_any_cast)
        {
213
            try
214
            {
215 216 217 218
                mpl::for_each<value_types>
                    (check_value_type<EdgeIndexMap>(_edge_map,
                                                    any_cast<edge_t>(key),
                                                    value, map));
219 220 221 222
            }
            catch (bad_any_cast)
            {
                ConstantPropertyMap<size_t,graph_property_tag> graph_index(0);
223 224 225 226 227
                mpl::for_each<value_types>
                    (check_value_type<ConstantPropertyMap<size_t,
                                                          graph_property_tag> >
                     (graph_index, any_cast<graph_property_tag>(key),
                      value, map));
228
            }
229
        }
230
        return DP_SMART_PTR<dynamic_property_map>(map);
Tiago Peixoto's avatar
Tiago Peixoto committed
231 232 233 234 235 236
    }

    VertexIndexMap _vertex_map;
    EdgeIndexMap _edge_map;
};

237

Tiago Peixoto's avatar
Tiago Peixoto committed
238 239
// this graph wraps an UndirectedAdaptor, but overrides the underlying
// edge_descriptor type with the original type. This will make the edge property
240
// maps compatible with the original graph, but will break some things which
Tiago Peixoto's avatar
Tiago Peixoto committed
241 242 243 244 245 246 247 248 249 250
// are not relevant here

template <class Graph>
struct FakeUndirGraph: public UndirectedAdaptor<Graph>
{
    FakeUndirGraph(const Graph &g): UndirectedAdaptor<Graph>(g) {}
    FakeUndirGraph(UndirectedAdaptor<Graph> &g): UndirectedAdaptor<Graph>(g) {}
};

template <class Graph>
251 252
struct FakeEdgeIterator:
    public graph_traits<UndirectedAdaptor<Graph> >::edge_iterator
Tiago Peixoto's avatar
Tiago Peixoto committed
253
{
254 255 256 257
    typedef typename graph_traits<FakeUndirGraph<Graph> >::edge_descriptor
        edge_descriptor;
    typedef typename graph_traits<UndirectedAdaptor<Graph> >::edge_iterator
        edge_iterator;
Tiago Peixoto's avatar
Tiago Peixoto committed
258 259 260 261
    FakeEdgeIterator(){}
    FakeEdgeIterator(edge_iterator e): edge_iterator(e) {}
    edge_descriptor operator*() const
    {
262
        return edge_descriptor(*edge_iterator(*this));
263
    }
Tiago Peixoto's avatar
Tiago Peixoto committed
264 265 266

};

267

Tiago Peixoto's avatar
Tiago Peixoto committed
268 269
namespace boost {
template <class Graph>
270 271
struct graph_traits<FakeUndirGraph<Graph> >
    : public graph_traits<UndirectedAdaptor<Graph> >
Tiago Peixoto's avatar
Tiago Peixoto committed
272 273 274 275 276 277 278 279
{
    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;
    typedef FakeEdgeIterator<Graph> edge_iterator;
};
}


//==============================================================================
280
// ReadFromFile(file, pfile, format)
Tiago Peixoto's avatar
Tiago Peixoto committed
281 282
//==============================================================================

283 284 285
void build_stream
    (boost::iostreams::filtering_stream<boost::iostreams::input>& stream,
     const string& file,  python::object& pfile, std::ifstream& file_stream)
Tiago Peixoto's avatar
Tiago Peixoto committed
286
{
287 288 289 290
    stream.reset();
    if (file == "-")
        stream.push(std::cin);
    else
Tiago Peixoto's avatar
Tiago Peixoto committed
291
    {
292
        if (pfile == python::object())
293
        {
294 295
            file_stream.open(file.c_str(), std::ios_base::in |
                             std::ios_base::binary);
296 297
            file_stream.exceptions(ios_base::badbit | ios_base::failbit);
            if (boost::ends_with(file,".gz"))
298
                stream.push(boost::iostreams::gzip_decompressor());
299
            if (boost::ends_with(file,".bz2"))
300
                stream.push(boost::iostreams::bzip2_decompressor());
301 302
            stream.push(file_stream);
        }
303 304 305 306 307 308 309 310 311 312
        else
        {
            python_file_device src(pfile);
            stream.push(src);
        }
    }
    stream.exceptions(ios_base::badbit);
}


313
python::tuple GraphInterface::ReadFromFile(string file, python::object pfile,
314 315 316 317
                                           string format,
                                           python::list ignore_vp,
                                           python::list ignore_ep,
                                           python::list ignore_gp)
318
{
319
    if (format != "dot" && format != "xml" && format != "gml")
Tiago Peixoto's avatar
Tiago Peixoto committed
320
        throw ValueException("error reading from file '" + file +
321 322 323 324 325 326 327
                             "': requested invalid format '" + format + "'");
    try
    {
        boost::iostreams::filtering_stream<boost::iostreams::input>
            stream;
        std::ifstream file_stream;
        build_stream(stream, file, pfile, file_stream);
328

329 330 331 332 333 334 335 336
        set<string> ivp, iep, igp;
        for (int i = 0; i < len(ignore_vp); ++i)
            ivp.insert(python::extract<string>(ignore_vp[i]));
        for (int i = 0; i < len(ignore_ep); ++i)
            iep.insert(python::extract<string>(ignore_ep[i]));
        for (int i = 0; i < len(ignore_gp); ++i)
            igp.insert(python::extract<string>(ignore_gp[i]));

337 338 339
        create_dynamic_map<vertex_index_map_t,edge_index_map_t>
            map_creator(_vertex_index, _edge_index);
        dynamic_properties dp(map_creator);
340
        *_mg = multigraph_t();
341

342
        if (format == "dot")
343 344
            _directed = read_graphviz(stream, *_mg, dp, "vertex_name", true,
                                     ivp, iep, igp);
345
        else if (format == "xml")
346 347
            _directed = read_graphml(stream, *_mg, dp, true, true, true,
                                     ivp, iep, igp);
348
        else if (format == "gml")
349
            _directed = read_gml(stream, *_mg, dp, ivp, iep, igp);
350

351 352 353 354
        python::dict vprops, eprops, gprops;
        for(typeof(dp.begin()) iter = dp.begin(); iter != dp.end(); ++iter)
        {
            if (iter->second->key() == typeid(vertex_t))
355
                vprops[iter->first] = find_property_map(*iter->second,
356 357
                                                       _vertex_index);
            else if (iter->second->key() == typeid(edge_t))
358
                eprops[iter->first] = find_property_map(*iter->second,
359 360
                                                       _edge_index);
            else
361
                gprops[iter->first] = find_property_map(*iter->second,
362 363 364
                                                        _graph_index);
        }
        return python::make_tuple(vprops, eprops, gprops);
Tiago Peixoto's avatar
Tiago Peixoto committed
365 366 367
    }
    catch (ios_base::failure &e)
    {
Tiago Peixoto's avatar
Tiago Peixoto committed
368
        throw IOException("error reading from file '" + file + "':" + e.what());
Tiago Peixoto's avatar
Tiago Peixoto committed
369
    }
370 371 372 373
    catch (parse_error &e)
    {
        throw IOException("error reading from file '" + file + "':" + e.what());
    }
374 375 376 377
    catch (gml_parse_error &e)
    {
        throw IOException("error reading from file '" + file + "':" + e.what());
    }
Tiago Peixoto's avatar
Tiago Peixoto committed
378 379
};

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
template <class IndexMap>
string graphviz_insert_index(dynamic_properties& dp, IndexMap index_map,
                             bool insert = true)
{
    typedef GraphInterface::vertex_t vertex_t;
    bool found = false;
    for(typeof(dp.begin()) iter = dp.begin(); iter != dp.end();
        ++iter)
        if (iter->first == "vertex_name" &&
            iter->second->key() == typeid(vertex_t))
            found = true;
    if (!found && insert)
        dp.property("vertex_id", index_map);
    if (found)
        return "vertex_name";
    else
        return "vertex_id";
}

399 400
// writes a graph to a file

Tiago Peixoto's avatar
Tiago Peixoto committed
401 402 403
struct write_to_file
{
    template <class Graph, class IndexMap>
404
    void operator()(ostream& stream, Graph& g, IndexMap index_map,
405
                    dynamic_properties& dp, const string& format) const
Tiago Peixoto's avatar
Tiago Peixoto committed
406
    {
407 408
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

409
        if (format == "dot")
410
        {
411
            string name = graphviz_insert_index(dp, index_map, false);
412
            write_graphviz(stream, g, dp, name);
413
        }
414
        else if (format == "xml")
415
        {
416
            write_graphml(stream, g, index_map, dp, true);
417
        }
418 419 420 421
        else if (format == "gml")
        {
            write_gml(stream, g, index_map, dp);
        }
Tiago Peixoto's avatar
Tiago Peixoto committed
422 423 424 425 426 427
    }
};

struct write_to_file_fake_undir: public write_to_file
{
    template <class Graph, class IndexMap>
428
    void operator()(ostream& stream, Graph& g, IndexMap index_map,
429
                    dynamic_properties& dp, const string& format) const
Tiago Peixoto's avatar
Tiago Peixoto committed
430
    {
431
        typedef typename Graph::original_graph_t graph_t;
432
        FakeUndirGraph<graph_t> ug(g);
433
        write_to_file(*this)(stream, ug, index_map, dp, format);
Tiago Peixoto's avatar
Tiago Peixoto committed
434 435 436 437 438 439
    }
};

struct generate_index
{
    template <class Graph, class IndexMap>
440
    void operator()(Graph& g, IndexMap index_map) const
Tiago Peixoto's avatar
Tiago Peixoto committed
441
    {
442 443
        size_t n = 0;
        typename graph_traits<Graph>::vertex_iterator v, v_end;
444
        for( tie(v, v_end) = vertices(g); v != v_end; ++v)
445
            index_map[*v] = n++;
Tiago Peixoto's avatar
Tiago Peixoto committed
446 447 448
    }
};

449
void GraphInterface::WriteToFile(string file, python::object pfile,
450
                                 string format, python::list props)
Tiago Peixoto's avatar
Tiago Peixoto committed
451
{
452
    if (format != "xml" && format != "dot" && format != "gml")
Tiago Peixoto's avatar
Tiago Peixoto committed
453
        throw ValueException("error writing to file '" + file +
454
                             "': requested invalid format '" + format + "'");
Tiago Peixoto's avatar
Tiago Peixoto committed
455 456
    try
    {
457 458 459 460 461 462
        boost::iostreams::filtering_stream<boost::iostreams::output> stream;
        std::ofstream file_stream;
        if (file == "-")
            stream.push(std::cout);
        else
        {
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
            if (pfile == python::object())
            {
                file_stream.open(file.c_str(), std::ios_base::out |
                                 std::ios_base::binary);
                file_stream.exceptions(ios_base::badbit | ios_base::failbit);
                if (boost::ends_with(file,".gz"))
                    stream.push(boost::iostreams::gzip_compressor());
                if (boost::ends_with(file,".bz2"))
                    stream.push(boost::iostreams::bzip2_compressor());
                stream.push(file_stream);
            }
            else
            {
                python_file_device sink(pfile);
                stream.push(sink);
            }
479 480 481
        }
        stream.exceptions(ios_base::badbit | ios_base::failbit);

482 483 484 485 486 487 488 489
        dynamic_properties dp;
        for (int i = 0; i < len(props); ++i)
        {
            dynamic_property_map* pmap =
                any_cast<dynamic_property_map*>
                (python::extract<boost::any>
                 (props[i][1].attr("get_dynamic_map")()));
            dp.insert(python::extract<string>(props[i][0]),
490
                      DP_SMART_PTR<dynamic_property_map>(pmap));
491
        }
492 493 494 495

        if (IsVertexFilterActive())
        {
            // vertex indexes must be between the [0, HardNumVertices(g)] range
496
            typedef tr1::unordered_map<vertex_t, size_t>  map_t;
497 498
            map_t vertex_to_index;
            associative_property_map<map_t> index_map(vertex_to_index);
499 500
            run_action<>()(*this, boost::bind<void>(generate_index(),
                                                    _1, index_map))();
501
            if (format == "dot")
502 503
                graphviz_insert_index(dp, index_map);

504
            if (GetDirected())
505
                run_action<detail::always_directed>()
506 507 508
                    (*this, boost::bind<void>(write_to_file(),
                                              boost::ref(stream), _1,
                                              index_map, boost::ref(dp),
509
                                              format))();
510
            else
511
                run_action<detail::never_directed>()
512 513
                    (*this,boost::bind<void>(write_to_file_fake_undir(),
                                             boost::ref(stream), _1, index_map,
514
                                             boost::ref(dp), format))();
515 516 517
        }
        else
        {
518
            if (format == "dot")
519
                graphviz_insert_index(dp, _vertex_index);
520 521

            if (GetDirected())
522
                run_action<detail::always_directed>()
523 524 525
                    (*this, boost::bind<void>(write_to_file(),
                                              boost::ref(stream), _1,
                                              _vertex_index,  boost::ref(dp),
526
                                              format))();
527
            else
528
                run_action<detail::never_directed>()
529 530 531
                    (*this,boost::bind<void>(write_to_file_fake_undir(),
                                             boost::ref(stream), _1,
                                             _vertex_index, boost::ref(dp),
532
                                             format))();
533 534
        }
        stream.reset();
Tiago Peixoto's avatar
Tiago Peixoto committed
535 536 537
    }
    catch (ios_base::failure &e)
    {
Tiago Peixoto's avatar
Tiago Peixoto committed
538
        throw IOException("error writing to file '" + file + "':" + e.what());
Tiago Peixoto's avatar
Tiago Peixoto committed
539 540
    }
}