gml.hh 13.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-2012 Tiago de Paula Peixoto <tiago@skewed.de>
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#ifndef GML_HH
#define GML_HH

21 22 23 24 25 26 27 28
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/variant/recursive_variant.hpp>
29
#include <boost/variant/get.hpp>
30 31 32 33 34 35 36 37 38
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/foreach.hpp>
#include <boost/type_traits.hpp>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

39 40 41 42 43 44
#if (GCC_VERSION >= 40400)
#   include <tr1/unordered_map>
#else
#   include <boost/tr1/unordered_map.hpp>
#endif

45 46 47 48 49 50 51 52 53 54 55
namespace graph_tool{

using namespace std;
using namespace boost;

class gml_parse_error: public std::exception
{
public:
    gml_parse_error(const string& w): _what(w) {}
    ~gml_parse_error() throw() {}
    std::string what() {return _what;}
56

57 58 59 60 61 62 63 64 65 66 67 68 69
private:
    std::string _what;
};


template <class Graph>
class gml_state
{
public:
    gml_state(Graph& g, dynamic_properties& dp)
        : _g(g), _dp(dp), _directed(false) {}

    typedef boost::variant<std::string, int, double> val_t;
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 96 97 98 99 100
    // key / value mechanics
    void push_key(const std::string& key)
    {
        _stack.push_back(make_pair(key, prop_list_t()));
    }

    void push_value(const val_t& value)
    {
        if (_stack.empty())
            return;
        std::string k = _stack.back().first;
        _stack.pop_back();
        if (!_stack.empty())
            _stack.back().second[k] = value;
    }

    // actual parsing
    void finish_list()
    {
        if (_stack.empty())
            return;

        std::string &k = _stack.back().first;
        if (k == "node")
        {
            int id;
            if (_stack.back().second.find("id") == _stack.back().second.end())
                throw gml_parse_error("node does not have an id");
            try
            {
101
                id = boost::get<double>(_stack.back().second["id"]);
102 103 104
            }
            catch (bad_get)
            {
105
                throw gml_parse_error("invalid node id");
106 107 108 109 110 111 112 113 114 115 116
            }

            typename graph_traits<Graph>::vertex_descriptor v = get_vertex(id);

            // put properties
            for (typeof(_stack.back().second.begin()) iter = _stack.back().second.begin();
                 iter != _stack.back().second.end(); ++iter)
            {
                if (iter->first == "id")
                    continue;
                try
117 118
                {
                    put(iter->first, _dp, v, boost::get<string>(iter->second));
119 120 121
                }
                catch (bad_get)
                {
122
                    put(iter->first, _dp, v, boost::get<double>(iter->second));
123 124 125 126 127 128 129 130 131 132 133 134 135
                }
            }
        }
        else if (k == "edge")
        {
            int source, target;
            if (_stack.back().second.find("source") ==
                _stack.back().second.end() ||
                _stack.back().second.find("target") ==
                _stack.back().second.end())
                throw gml_parse_error("edge does not have source and target ids");
            try
            {
136 137
                source = boost::get<double>(_stack.back().second["source"]);
                target = boost::get<double>(_stack.back().second["target"]);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
            }
            catch (bad_get)
            {
                throw gml_parse_error("invalid source and target ids");
            }

            typename graph_traits<Graph>::vertex_descriptor s, t;
            s = get_vertex(source);
            t = get_vertex(target);

            typename graph_traits<Graph>::edge_descriptor e =
                add_edge(s, t, _g).first;

            // put properties
            for (typeof(_stack.back().second.begin()) iter = _stack.back().second.begin();
                 iter != _stack.back().second.end(); ++iter)
            {
                if (iter->first == "id" || iter->first == "source" || iter->first == "target")
                    continue;
                try
158 159
                {
                    put(iter->first, _dp, e, boost::get<string>(iter->second));
160 161 162
                }
                catch (bad_get)
                {
163
                    put(iter->first, _dp, e, boost::get<double>(iter->second));
164 165
                }
            }
166

167 168 169 170 171 172 173 174
        }
        else if (k == "graph")
        {
            // put properties
            for (typeof(_stack.back().second.begin()) iter = _stack.back().second.begin();
                 iter != _stack.back().second.end(); ++iter)
            {
                if (iter->first == "directed")
175
                    _directed = boost::get<double>(iter->second);
176
                try
177 178
                {
                    put(iter->first, _dp, graph_property_tag(), boost::get<string>(iter->second));
179 180 181
                }
                catch (bad_get)
                {
182
                    put(iter->first, _dp, graph_property_tag(), boost::get<double>(iter->second));
183 184
                }
            }
185

186 187 188 189 190 191 192 193 194 195 196
        }
        _stack.pop_back();
    }

    typename graph_traits<Graph>::vertex_descriptor get_vertex(size_t index)
    {
        if (_vmap.find(index) == _vmap.end())
            _vmap[index] = add_vertex(_g);
        return _vmap[index];
    }

197 198

    bool is_directed()
199 200 201
    {
        return _directed;
    }
202

203 204 205 206 207

private:
    Graph& _g;
    dynamic_properties& _dp;
    bool _directed;
208
    tr1::unordered_map<int, typename graph_traits<Graph>::vertex_descriptor> _vmap;
209 210

    // the stack holds the keys, and its properties (but omits nested lists)
211
    typedef tr1::unordered_map<std::string, val_t> prop_list_t;
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    vector<pair<std::string,  prop_list_t> > _stack;
};


template <class Iterator, class Graph, class Skipper>
struct gml : spirit::qi::grammar<Iterator, void(), Skipper>
{
    gml(Graph& g, dynamic_properties& dp) : gml::base_type(start), _state(g, dp)
    {
        using namespace spirit;
        using spirit::ascii::char_;

        unesc_str = spirit::lexeme['"' >> *(unesc_char | (spirit::qi::char_ - "\"") | "\\x" >> qi::hex) >> '"'];
        unesc_char.add("\\a", '\a')("\\b", '\b')("\\f", '\f')("\\n", '\n')
            ("\\r", '\r')("\\t", '\t')("\\v", '\v')("\\\\", '\\')
            ("\\\'", '\'')("\\\"", '\"');
        key_identifier %= spirit::lexeme[((+spirit::qi::alnum) >> *spirit::qi::alnum)];
        key = key_identifier
            [boost::bind(&gml_state<Graph>::push_key, &_state, ::_1)];
        value_identifier %= (spirit::lexeme[spirit::qi::double_] | unesc_str);
        value %= value_identifier
            [boost::bind(&gml_state<Graph>::push_value, &_state, ::_1)];
        list_identifier = *(key >> (value | "[" >> list >> "]"));
        list = list_identifier
            [boost::bind(&gml_state<Graph>::finish_list, &_state)];
        start = list;
    }

    typedef boost::variant<std::string, double> val_t;

    spirit::qi::rule<Iterator, std::string(), Skipper> unesc_str;
    spirit::qi::symbols<char const, char const> unesc_char;
    spirit::qi::rule<Iterator, std::string(), Skipper> key, key_identifier;
    spirit::qi::rule<Iterator, val_t(), Skipper> value, value_identifier;
    spirit::qi::rule<Iterator, void(), Skipper> list, list_identifier;
    spirit::qi::rule<Iterator, void(), Skipper> start;
248

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    gml_state<Graph> _state;
};

template <class Iterator, class Graph, class Skipper>
bool parse_grammar(Iterator begin, Iterator end, Graph& g,
                   dynamic_properties& dp, Skipper skip)
{
    using namespace spirit;
    gml<spirit::istream_iterator, Graph, Skipper> parser(g, dp);
    bool ok = qi::phrase_parse(begin, end, parser, skip);
    if (!ok)
        throw gml_parse_error("invalid syntax");
    return parser._state.is_directed();
}


template <class Graph>
bool read_gml(istream& in, Graph& g, dynamic_properties& dp)
{
    using namespace spirit;

    in >> std::noskipws;
    spirit::istream_iterator begin(in);
    spirit::istream_iterator end;

    bool directed =
        parse_grammar(begin, end, g, dp,
                      (ascii::space |'#' >> *(ascii::char_ - qi::eol) >> qi::eol));

    in >> std::noskipws;
    std::stringstream input;
    input << in.rdbuf();
    return directed;
}

struct get_str
{
    template <typename ValueType>
    void operator()(const boost::any& val, std::string& sval, ValueType) const
    {
289
        try
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
        {
            ValueType v = any_cast<ValueType>(val);
            if (is_same<ValueType, python::object>::value)
            {
                sval = lexical_cast<string>(v);
            }
            else
            {
                stringstream s;
                s << v;
                sval = s.str();
            }

            if (!is_scalar<ValueType>::value)
            {
                replace_all(sval, "\"", "\\\"");
                sval = "\"" + sval + "\"";
307
            }
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
        }
        catch (bad_any_cast)
        {
        }
    }
};

template <typename ValueTypes, typename Descriptor>
std::string print_val(dynamic_property_map& pmap, const Descriptor& v)
{
    std::string val;
    boost::any oval = pmap.get(v);
    mpl::for_each<ValueTypes>(bind<void>(get_str(), ref(oval),
                                         ref(val), _1));
    return val;
}


template <typename Graph, typename VertexIndexMap>
void write_gml(std::ostream& out, const Graph& g, VertexIndexMap vertex_index,
               const dynamic_properties& dp)
{
    typedef typename graph_traits<Graph>::directed_category directed_category;
    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;

    typedef mpl::vector<bool, uint8_t, int8_t, uint32_t, int32_t,
                        uint64_t, int64_t, float, double, long double,
                        std::vector<uint8_t>, std::vector<int32_t>,
                        std::vector<int64_t>, std::vector<double>,
                        std::vector<long double>, std::vector<std::string>,
                        std::string, python::object> value_types;

    BOOST_STATIC_CONSTANT(bool, graph_is_directed =
                          (is_convertible<directed_category*,
                                          directed_tag*>::value));

    out << "graph [" << endl;

    if (graph_is_directed)
        out << "   directed " << 1 << endl;

    for (dynamic_properties::const_iterator i = dp.begin(); i != dp.end();
         ++i)
    {
        if (i->second->key() == typeid(graph_property_tag))
        {
            std::string val = print_val<value_types>(*i->second,
                                                     graph_property_tag());
            if (val.empty())
                continue;
            out << "   " << i->first << " " << val << endl;
        }
    }

    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
    vertex_iterator v, v_end;
    for (tie(v, v_end) = vertices(g); v != v_end; ++v)
    {
        out << "   node [" << endl;
        out << "      id " << get(vertex_index, *v) << endl;

        for (dynamic_properties::const_iterator i = dp.begin(); i != dp.end();
             ++i)
        {
            if (i->second->key() == typeid(vertex_descriptor))
            {
                std::string val = print_val<value_types>(*i->second, *v);
                if (val.empty())
                    continue;
                out << "      " << i->first << " " << val << endl;
            }
        }
        out << "   ]" << endl;
    }

    typedef typename graph_traits<Graph>::edge_iterator edge_iterator;
    edge_iterator e, e_end;
    typename graph_traits<Graph>::edges_size_type edge_count = 0;
    for (tie(e, e_end) = edges(g); e != e_end; ++e)
    {
        out << "   edge [" << endl;
        out << "      id " << edge_count++ << endl;
        out << "      source " << get(vertex_index, source(*e, g)) << endl;
        out << "      target " << get(vertex_index, target(*e, g)) << endl;

        for (dynamic_properties::const_iterator i = dp.begin(); i != dp.end();
             ++i)
        {
            if (i->second->key() == typeid(edge_descriptor))
            {
                std::string val = print_val<value_types>(*i->second, *e);
                if (val.empty())
                    continue;
                out << "      " << i->first << " " << val << endl;
            }
        }
        out << "   ]" << endl;
    }
    out << "]" << endl;
}


template <typename Graph>
void write_gml(std::ostream& out, const Graph& g, const dynamic_properties& dp)
{
    write_gml(out, g, get(vertex_index, g), dp);
}

} // namespace graph_tool
418 419

#endif // GML_HH