graphml.cpp 11.6 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
// Copyright (C) 2006  Tiago de Paula Peixoto <tiago@forked.de>
2
// Copyright (C) 2004  The Trustees of Indiana University.
Tiago Peixoto's avatar
Tiago Peixoto committed
3
//
4
5
6
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
Tiago Peixoto's avatar
Tiago Peixoto committed
7
8
9
10
11

//  Authors: Douglas Gregor
//           Andrew Lumsdaine
//           Tiago de Paula Peixoto

12
#include <boost/variant.hpp>
13
14
#include <expat.h>
#include <boost/graph/graphml.hpp>
15
#include <boost/algorithm/string/replace.hpp>
Tiago Peixoto's avatar
Tiago Peixoto committed
16

17
using namespace boost;
Tiago Peixoto's avatar
Tiago Peixoto committed
18
19
20
21

class graphml_reader
{
public:
22
    graphml_reader(mutate_graph& g) 
23
        : m_g(g), m_canonical_vertices(false) { }
Tiago Peixoto's avatar
Tiago Peixoto committed
24
25
26
    
    void run(std::istream& in)
    {
27
        const int buffer_size = 4096;
28
29
30
31
        m_parser = XML_ParserCreateNS(0,'|');
        XML_SetElementHandler(m_parser, &on_start_element, &on_end_element);
        XML_SetCharacterDataHandler(m_parser, &on_character_data);
        XML_SetUserData(m_parser, this);
32
        char buffer[buffer_size];
33
34

        bool okay = true;
35
36
37
        do 
        {
            in.read(buffer, buffer_size);
38
            okay = XML_Parse(m_parser, buffer, in.gcount(), in.gcount() == 0);
39
        } 
40
        while (okay && in.good());
41

42
        if (!okay) 
43
44
        {
            std::stringstream s;
45
46
47
            s << "on line " << XML_GetCurrentLineNumber(m_parser) 
              <<", column " << XML_GetCurrentColumnNumber(m_parser)
              << ": " << XML_ErrorString(XML_GetErrorCode(m_parser));
48
49
            throw parse_error(s.str());
        }
50
        XML_ParserFree(m_parser);
Tiago Peixoto's avatar
Tiago Peixoto committed
51
52
53
54
55
    }

private:
    /// The kinds of keys. Not all of these are supported
    enum key_kind { 
56
57
58
59
60
61
62
        graph_key, 
        node_key, 
        edge_key,
        hyperedge_key,
        port_key,
        endpoint_key, 
        all_key
Tiago Peixoto's avatar
Tiago Peixoto committed
63
64
65
66
    };

    static void 
    on_start_element(void* user_data, const XML_Char *c_name,
67
                     const XML_Char **atts)
Tiago Peixoto's avatar
Tiago Peixoto committed
68
    {
69
70
71
        graphml_reader* self = static_cast<graphml_reader*>(user_data);

        std::string name(c_name);
72
        replace_first(name, "http://graphml.graphdrawing.org/xmlns|", "");
73
74
        
        if (name == "edge") 
75
76
        {
            std::string id;
77
            std::string source, target;
78
79
            while (*atts) 
            {
80
81
82
83
                std::string name = *atts++;
                std::string value = *atts++;

                if (name == "id") id = value;
84
85
86
                else if (name == "source") source = value;
                else if (name == "target") target = value;
                else if (name == "directed") 
87
                {
88
89
                    bool edge_is_directed = (value == "directed");
                    if (edge_is_directed != self->m_g.is_directed()) 
90
                    {
91
92
93
94
                        if (edge_is_directed) 
                            throw directed_graph_error();
                        else
                            throw undirected_graph_error();
95
96
                    }
                }
97
98
            }

99
100
101
            self->m_active_descriptor = self->m_edge.size();
            self->handle_edge(source, target);
        }
102
103
104
105
106
107
        else if (name == "node") 
        {
            std::string id;

            while (*atts) 
            {
108
109
110
111
                std::string name = *atts++;
                std::string value = *atts++;
                
                if (name == "id") id = value;
112
113
114
115
116
            }

            self->handle_vertex(id);
            self->m_active_descriptor = id;
        } 
117
118
119
120
121
122
123
124
125
126
127
        else if (name == "data") 
        {
            while (*atts) 
            {
                std::string name = *atts++;
                std::string value = *atts++;

                if (name == "key") self->m_active_key = value;
            }
        }
        else if (name == "key") 
128
129
        {
            std::string id;
130
131
132
133
            std::string key_name;
            std::string key_type;
            key_kind kind = all_key;

134
135
            while (*atts) 
            {
136
137
138
139
                std::string name = *atts++;
                std::string value = *atts++;

                if (name == "id") id = value;
140
141
142
                else if (name == "attr.name") key_name = value;
                else if (name == "attr.type") key_type = value;
                else if (name == "for") 
143
                {
144
145
146
147
148
149
150
151
                    if (value == "graph") kind = graph_key;
                    else if (value == "node") kind = node_key;
                    else if (value == "edge") kind = edge_key;
                    else if (value == "hyperedge") kind = hyperedge_key;
                    else if (value == "port") kind = port_key;
                    else if (value == "endpoint") kind = endpoint_key;
                    else if (value == "all") kind = all_key;
                    else 
152
                    {
153
                        std::stringstream s;
154
155
156
157
                        s << "on line " 
                          << XML_GetCurrentLineNumber(self->m_parser) 
                          << ", column " 
                          << XML_GetCurrentColumnNumber(self->m_parser)
158
159
                          << ": unrecognized key kind '" << value << "'";
                        throw parse_error(s.str());
160
161
                    }
                }
162
163
            }

164
165
166
167
            self->m_keys[id] = kind;
            self->m_key_name[id] = key_name;
            self->m_key_type[id] = key_type;
            self->m_active_key = id;
168
169
170
171
172
        } 
        else if (name == "graph") 
        {
            while (*atts) 
            {
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
                std::string name = *atts++;
                std::string value = *atts++;
                
                if (name == "edgedefault") 
                {
                    bool edge_is_directed = (value == "directed");
                    if (edge_is_directed != self->m_g.is_directed()) 
                    {
                        if (edge_is_directed) 
                            throw directed_graph_error();
                        else
                            throw undirected_graph_error();
                    }
                }
                else if (name == "parse.nodeids")
                {
                    self->m_canonical_vertices = (value == "canonical");
                }
191
192
193
194
195
            }
            self->m_active_descriptor = "";
        } 

        self->m_character_data.clear();
Tiago Peixoto's avatar
Tiago Peixoto committed
196
197
198
199
200
    }
    
    static void
    on_end_element(void* user_data, const XML_Char *c_name)
    {
201
        graphml_reader* self = static_cast<graphml_reader*>(user_data);
202

203
        std::string name(c_name);
204
        replace_first(name, "http://graphml.graphdrawing.org/xmlns|", "");
205
206

        if (name == "data") 
207
        {            
208
            self->handle_property(self->m_active_key, self->m_active_descriptor,
209
                                  self->m_character_data);
210
211
212
213
214
        } 
        else if (name == "default")
        {
            self->m_key_default[self->m_active_key] = self->m_character_data;
        }
Tiago Peixoto's avatar
Tiago Peixoto committed
215
216
217
218
219
    }

    static void
    on_character_data(void* user_data, const XML_Char* s, int len)
    {
220
221
        graphml_reader* self = static_cast<graphml_reader*>(user_data);
        self->m_character_data.append(s, len);
Tiago Peixoto's avatar
Tiago Peixoto committed
222
223
224
225
226
    }

    void 
    handle_vertex(const std::string& v)
    {
227
228
229
230
231
232
233
234
235
        bool is_new = false;

        if (m_canonical_vertices)
        {
            size_t id;

            //strip leading "n" from name
            try 
            {
236
                id = lexical_cast<size_t>(std::string(v,1));
237
238
239
            }
            catch (bad_lexical_cast)
            {
240
241
242
243
244
                std::stringstream s;
                s << "on line " << XML_GetCurrentLineNumber(m_parser) 
                  << ", column " << XML_GetCurrentColumnNumber(m_parser)
                  << ": invalid vertex: " << v;
                throw parse_error(s.str());
245
246
247
248
            }
            
            while(id >= m_canonical_vertex.size())
            {
249
250
                m_canonical_vertex.push_back(m_g.do_add_vertex());
                is_new = true;
251
252
253
254
255
256
            }
        }
        else
        {
            if (m_vertex.find(v) == m_vertex.end())
            {
257
258
                m_vertex[v] = m_g.do_add_vertex();
                is_new = true;
259
260
261
262
263
264
            }
        }

        if (is_new)
        {
            std::map<std::string, std::string>::iterator iter;
265
266
            for (iter = m_key_default.begin(); iter != m_key_default.end(); 
                 ++iter)
267
            {
268
                if (m_keys[iter->first] == node_key)
269
                    handle_property(iter->first, v, iter->second);
270
271
            }
        }
Tiago Peixoto's avatar
Tiago Peixoto committed
272
273
    }

274
    any
Tiago Peixoto's avatar
Tiago Peixoto committed
275
276
    get_vertex_descriptor(const std::string& v)
    {
277
278
279
280
281
282
283
        if (m_canonical_vertices)
        {
            //strip leading "n" from name
            size_t id = lexical_cast<size_t>(std::string(v,1));
            return m_canonical_vertex[id];
        }
        else
284
        {            
285
286
            return m_vertex[v];
        }
Tiago Peixoto's avatar
Tiago Peixoto committed
287
288
289
    }

    void 
290
    handle_edge(const std::string& u, const std::string& v)
Tiago Peixoto's avatar
Tiago Peixoto committed
291
    {
292
293
        handle_vertex(u);
        handle_vertex(v);
Tiago Peixoto's avatar
Tiago Peixoto committed
294

295
296
297
        any source, target;
        source = get_vertex_descriptor(u);
        target = get_vertex_descriptor(v);
Tiago Peixoto's avatar
Tiago Peixoto committed
298

299
300
301
302
303
        any edge;
        bool added;
        tie(edge, added) = m_g.do_add_edge(source, target);
        if (!added)
            throw bad_parallel_edge(u, v);
Tiago Peixoto's avatar
Tiago Peixoto committed
304

305
306
307
        size_t e = m_edge.size();
        m_edge.push_back(edge);
        
308
309
310
311
        std::map<std::string, std::string>::iterator iter;
        for (iter = m_key_default.begin(); iter != m_key_default.end(); ++iter)
        {
            if (m_keys[iter->first] == edge_key)
312
                handle_property(iter->first, e, iter->second);
313
        }
314
    }
Tiago Peixoto's avatar
Tiago Peixoto committed
315

316
317
318
    void handle_property(const std::string& key_id, 
                         const variant<std::string,size_t>& descriptor, 
                         const std::string& value)
Tiago Peixoto's avatar
Tiago Peixoto committed
319
    {
320
        try 
321
        {
322
323
324
            if (get<std::string>(&descriptor))
            {
                if (get<std::string>(descriptor) == "")
325
326
                    m_g.set_graph_property(m_key_name[key_id], value, 
                                           m_key_type[key_id]);
327
                else
328
329
330
331
                    m_g.set_vertex_property(m_key_name[key_id], 
                                            get_vertex_descriptor
                                                (get<std::string>(descriptor)), 
                                            value, m_key_type[key_id]);
332
            }
333
            else
334
            {
335
336
337
338
                m_g.set_edge_property(m_key_name[key_id], 
                                      get_edge_descriptor
                                          (get<size_t>(descriptor)), 
                                      value, m_key_type[key_id]);
339
            }
340
        }
341
        catch (parse_error &e)
342
        {
343
344
345
346
347
            std::stringstream s;
            s << "on line " << XML_GetCurrentLineNumber(m_parser) 
              << ", column " << XML_GetCurrentColumnNumber(m_parser)
              << ": " << e.error;
            throw parse_error(s.str());
348
        }
Tiago Peixoto's avatar
Tiago Peixoto committed
349
350
    }

351
352
353
354
355
356
    any
    get_edge_descriptor(size_t e)
    {
        return m_edge[e];
    }

357
    mutate_graph& m_g;
Tiago Peixoto's avatar
Tiago Peixoto committed
358
359
360
    std::map<std::string, key_kind> m_keys;
    std::map<std::string, std::string> m_key_name;
    std::map<std::string, std::string> m_key_type;
361
362
363
    std::map<std::string, std::string> m_key_default;
    std::map<std::string, any> m_vertex;
    std::vector<any> m_canonical_vertex;
364
365
    std::vector<any> m_edge;
    variant<std::string, size_t> m_active_descriptor;
Tiago Peixoto's avatar
Tiago Peixoto committed
366
367
368
369
    std::string m_active_key;
    std::string m_character_data;
    bool m_canonical_vertices;
    bool m_canonical_edges;
370
    XML_Parser m_parser;
Tiago Peixoto's avatar
Tiago Peixoto committed
371
372
};

373
namespace boost
Tiago Peixoto's avatar
Tiago Peixoto committed
374
375
{
void
376
377
378
379
read_graphml(std::istream& in, mutate_graph& g)
{    
    graphml_reader reader(g);
    reader.run(in);
Tiago Peixoto's avatar
Tiago Peixoto committed
380
381
}
}