Coverage Report

Created: 2026-12-01 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/igraph/src/io/gml.c
Line
Count
Source
1
/*
2
   igraph library.
3
   Copyright (C) 2005-2022  The igraph development team
4
5
   This program is free software; you can redistribute it and/or modify
6
   it under the terms of the GNU General Public License as published by
7
   the Free Software Foundation; either version 2 of the License, or
8
   (at your option) any later version.
9
10
   This program is distributed in the hope that it will be useful,
11
   but WITHOUT ANY WARRANTY; without even the implied warranty of
12
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
   GNU General Public License for more details.
14
15
   You should have received a copy of the GNU General Public License
16
   along with this program; if not, write to the Free Software
17
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18
   02110-1301 USA
19
*/
20
21
#include "igraph_foreign.h"
22
23
#include "igraph_attributes.h"
24
#include "igraph_interface.h"
25
#include "igraph_memory.h"
26
#include "igraph_version.h"
27
28
#include "core/trie.h"
29
#include "graph/attributes.h"
30
#include "internal/hacks.h" /* strdup, strncasecmp */
31
#include "math/safe_intop.h"
32
33
#include "io/gml-header.h"
34
#include "io/parsers/gml-parser.h"
35
36
#include <ctype.h>
37
#include <time.h>
38
#include <string.h>
39
40
int igraph_gml_yylex_init_extra(igraph_i_gml_parsedata_t *user_defined, void *scanner);
41
int igraph_gml_yylex_destroy(void *scanner);
42
int igraph_gml_yyparse(igraph_i_gml_parsedata_t *context);
43
void igraph_gml_yyset_in(FILE *in_str, void *yyscanner);
44
45
/* Checks if a null-terminated string needs encoding or decoding.
46
 *
47
 * Encoding is needed when an " or & character is present.
48
 *
49
 * Decoding is needed when an &xyz; style entity is present, so it's sufficient to look
50
 * for & characters. " characters are never present in the raw strings returned by the
51
 * GML parser, so we can use the same function to detect the need for either encoding
52
 * or decoding.
53
 */
54
508k
static igraph_bool_t needs_coding(const char *str) {
55
32.9M
    while (*str) {
56
32.4M
        if (*str == '&' || *str == '"') {
57
19.3k
            return true;
58
19.3k
        }
59
32.3M
        str++;
60
32.3M
    }
61
489k
    return false;
62
508k
}
63
64
/* Encode & and " character in 'src' to &amp; and &quot;
65
 * '*dest' must be deallocated by the caller.
66
 */
67
9.67k
static igraph_error_t entity_encode(const char *src, char **dest, igraph_bool_t only_quot) {
68
9.67k
    igraph_int_t destlen = 0;
69
9.67k
    const char *s;
70
9.67k
    char *d;
71
72
81.2M
    for (s = src; *s != '\0'; s++, destlen++) {
73
81.2M
        switch (*s) {
74
1.28k
        case '&': /* &amp; */
75
1.28k
            if (! only_quot) {
76
1.28k
                destlen += 4;
77
1.28k
            }
78
1.28k
            break;
79
16.0M
        case '"': /* &quot; */
80
16.0M
            destlen += 5; break;
81
81.2M
        }
82
81.2M
    }
83
9.67k
    *dest = IGRAPH_CALLOC(destlen + 1, char);
84
9.67k
    IGRAPH_CHECK_OOM(*dest, "Not enough memory to encode string for GML export.");
85
81.2M
    for (s = src, d = *dest; *s != '\0'; s++, d++) {
86
81.2M
        switch (*s) {
87
1.28k
        case '&':
88
1.28k
            if (! only_quot) {
89
1.28k
                strcpy(d, "&amp;");
90
1.28k
                d += 4;
91
1.28k
            } else {
92
0
                *d = *s;
93
0
            }
94
1.28k
            break;
95
16.0M
        case '"':
96
16.0M
            strcpy(d, "&quot;"); d += 5; break;
97
65.2M
        default:
98
65.2M
            *d = *s;
99
81.2M
        }
100
81.2M
    }
101
9.67k
    *d = '\0';
102
9.67k
    return IGRAPH_SUCCESS;
103
9.67k
}
104
105
/* Decode the five standard predefined XML entities. Unknown entities or stray & characters
106
 * will be passed through unchanged. '*dest' must be deallocated by the caller.
107
 * If '*warned' is false, warnings will be issued for unsupported entities and
108
 * '*warned' will be set to true. This is to prevent a flood of warnings in some files.
109
 */
110
9.67k
static igraph_error_t entity_decode(const char *src, char **dest, igraph_bool_t *warned) {
111
9.67k
    const char *entity_names[] = {
112
9.67k
        "&quot;", "&amp;", "&apos;", "&lt;", "&gt;"
113
9.67k
    };
114
115
9.67k
    const char entity_values[] = {
116
9.67k
        '"', '&', '\'', '<', '>'
117
9.67k
    };
118
119
9.67k
    const int entity_count = sizeof entity_values / sizeof entity_values[0];
120
121
9.67k
    const char *s;
122
9.67k
    char *d;
123
9.67k
    size_t len = strlen(src);
124
9.67k
    *dest = IGRAPH_CALLOC(len+1, char); /* at most as much storage needed as for 'src' */
125
9.67k
    IGRAPH_CHECK_OOM(*dest, "Not enough memory to decode string during GML import.");
126
127
81.2M
    for (s = src, d = *dest; *s != '\0';) {
128
81.2M
        if (*s == '&') {
129
16.0M
            int i;
130
16.0M
            for (i=0; i < entity_count; i++) {
131
16.0M
                size_t entity_len = strlen(entity_names[i]);
132
16.0M
                if (!strncasecmp(s, entity_names[i], entity_len)) {
133
16.0M
                    *d++ = entity_values[i];
134
16.0M
                    s += entity_len;
135
16.0M
                    break;
136
16.0M
                }
137
16.0M
            }
138
            /* None of the known entities match, report warning and pass through unchanged. */
139
16.0M
            if (i == entity_count) {
140
0
                if (! *warned) {
141
0
                    const int max_entity_name_length = 34;
142
0
                    int j = 0;
143
0
                    while (s[j] != '\0' && s[j] != ';' && j < max_entity_name_length) {
144
0
                        j++;
145
0
                    }
146
0
                    if (s[j] == '\0' || j == max_entity_name_length) {
147
0
                        IGRAPH_WARNING("Unterminated entity or stray & character found, will be returned verbatim.");
148
0
                    } else {
149
0
                        IGRAPH_WARNINGF("One or more unknown entities will be returned verbatim (%.*s).", j+1, s);
150
0
                    }
151
0
                    *warned = true; /* warn only once */
152
0
                }
153
0
                *d++ = *s++;
154
0
            }
155
65.2M
        } else {
156
65.2M
            *d++ = *s++;
157
65.2M
        }
158
81.2M
    }
159
9.67k
    *d = '\0';
160
161
9.67k
    return IGRAPH_SUCCESS;
162
9.67k
}
163
164
88.0k
static igraph_real_t igraph_i_gml_toreal(igraph_gml_tree_t *node, igraph_int_t pos) {
165
88.0k
    igraph_i_gml_tree_type_t type = igraph_gml_tree_type(node, pos);
166
167
88.0k
    switch (type) {
168
87.1k
    case IGRAPH_I_GML_TREE_INTEGER:
169
87.1k
        return igraph_gml_tree_get_integer(node, pos);
170
908
    case IGRAPH_I_GML_TREE_REAL:
171
908
        return igraph_gml_tree_get_real(node, pos);
172
0
    case IGRAPH_I_GML_TREE_TREE:
173
0
        return IGRAPH_NAN; /* default value of NaN when composite is ignored */
174
0
    default:
175
        /* Must never reach here, regardless of the contents of the GML file. */
176
0
        IGRAPH_FATALF("Unexpected node type in GML tree, line %" IGRAPH_PRId ".",
177
88.0k
                      igraph_gml_tree_line(node, pos)); /* LCOV_EXCL_LINE */
178
88.0k
    }
179
88.0k
}
180
181
253k
static const char *igraph_i_gml_tostring(igraph_gml_tree_t *node, igraph_int_t pos) {
182
253k
    igraph_i_gml_tree_type_t type = igraph_gml_tree_type(node, pos);
183
253k
    static char tmp[100];
184
253k
    const char *p = tmp;
185
253k
    igraph_int_t i;
186
253k
    igraph_real_t d;
187
188
253k
    switch (type) {
189
455
    case IGRAPH_I_GML_TREE_INTEGER:
190
455
        i = igraph_gml_tree_get_integer(node, pos);
191
455
        snprintf(tmp, sizeof(tmp) / sizeof(char), "%" IGRAPH_PRId, i);
192
455
        break;
193
384
    case IGRAPH_I_GML_TREE_REAL:
194
384
        d = igraph_gml_tree_get_real(node, pos);
195
384
        igraph_real_snprintf_precise(tmp, sizeof(tmp) / sizeof(char), d);
196
384
        break;
197
252k
    case IGRAPH_I_GML_TREE_STRING:
198
252k
        p = igraph_gml_tree_get_string(node, pos);
199
252k
        break;
200
0
    case IGRAPH_I_GML_TREE_TREE:
201
0
        tmp[0] = '\0'; /* default value of "" when composite is ignored */
202
0
        break;
203
0
    default:
204
        /* Must never reach here, regardless of the contents of the GML file. */
205
0
        IGRAPH_FATALF("Unexpected node type in GML tree, line %" IGRAPH_PRId ".",
206
253k
                      igraph_gml_tree_line(node, pos)); /* LCOV_EXCL_LINE */
207
253k
    }
208
209
253k
    return p;
210
253k
}
211
212
3.33k
igraph_error_t igraph_i_gml_parsedata_init(igraph_i_gml_parsedata_t *context) {
213
3.33k
    context->depth = 0;
214
3.33k
    context->scanner = NULL;
215
3.33k
    context->tree = NULL;
216
3.33k
    context->errmsg[0] = '\0';
217
3.33k
    context->igraph_errno = IGRAPH_SUCCESS;
218
219
3.33k
    return IGRAPH_SUCCESS;
220
3.33k
}
221
222
3.33k
void igraph_i_gml_parsedata_destroy(igraph_i_gml_parsedata_t *context) {
223
3.33k
    if (context->tree != NULL) {
224
3.33k
        igraph_gml_tree_destroy(context->tree);
225
3.33k
        context->tree = NULL;
226
3.33k
    }
227
228
3.33k
    if (context->scanner != NULL) {
229
3.33k
        (void) igraph_gml_yylex_destroy(context->scanner);
230
3.33k
        context->scanner = NULL;
231
3.33k
    }
232
3.33k
}
233
234
/* Takes a vector of attribute records and removes those elements
235
 * whose type is unspecified, i.e. IGRAPH_ATTRIBUTE_UNSPECIFIED. */
236
10.0k
static igraph_error_t prune_unknown_attributes(igraph_attribute_record_list_t *attrs) {
237
10.0k
    igraph_int_t i, n;
238
10.0k
    igraph_vector_int_t to_remove;
239
240
10.0k
    IGRAPH_VECTOR_INT_INIT_FINALLY(&to_remove, 0);
241
242
10.0k
    n = igraph_attribute_record_list_size(attrs);
243
16.6k
    for (i = 0; i < n; i++) {
244
6.66k
        igraph_attribute_record_t *atrec = igraph_attribute_record_list_get_ptr(attrs, i);
245
6.66k
        if (atrec->type == IGRAPH_ATTRIBUTE_UNSPECIFIED) {
246
0
            IGRAPH_CHECK(igraph_vector_int_push_back(&to_remove, i));
247
0
        }
248
6.66k
    }
249
250
10.0k
    n = igraph_vector_int_size(&to_remove);
251
10.0k
    for (i = n - 1; i >= 0; i--) {
252
0
        igraph_attribute_record_list_discard(attrs, VECTOR(to_remove)[i]);
253
0
    }
254
255
10.0k
    igraph_vector_int_destroy(&to_remove);
256
10.0k
    IGRAPH_FINALLY_CLEAN(1);
257
258
10.0k
    return IGRAPH_SUCCESS;
259
10.0k
}
260
261
/* Converts an integer id to an optionally prefixed string id. */
262
765k
static const char *strid(igraph_int_t id, const char *prefix) {
263
765k
    static char name[100];
264
765k
    snprintf(name, sizeof(name) / sizeof(char) - 1, "%s%" IGRAPH_PRId, prefix, id);
265
765k
    return name;
266
765k
}
267
268
/* Creates an empty attribute record or if it exists, updates its type as needed.
269
 * 'name' is the attribute name. 'type' is the current type in the GML tree,
270
 * which will determine the igraph attribute type to use. */
271
static igraph_error_t create_or_update_attribute(const char *name,
272
                                                 igraph_i_gml_tree_type_t type,
273
                                                 igraph_trie_t *attrnames,
274
341k
                                                 igraph_attribute_record_list_t *attrs) {
275
276
341k
    igraph_int_t trieid, triesize = igraph_trie_size(attrnames);
277
341k
    igraph_attribute_type_t desired_type;
278
279
341k
    IGRAPH_CHECK(igraph_trie_get(attrnames, name, &trieid));
280
341k
    if (trieid == triesize) {
281
        /* new attribute */
282
6.66k
        igraph_attribute_record_t atrec;
283
284
6.66k
        if (type == IGRAPH_I_GML_TREE_INTEGER || type == IGRAPH_I_GML_TREE_REAL) {
285
3.88k
            desired_type = IGRAPH_ATTRIBUTE_NUMERIC;
286
3.88k
        } else if (type == IGRAPH_I_GML_TREE_STRING) {
287
2.78k
            desired_type = IGRAPH_ATTRIBUTE_STRING;
288
2.78k
        } else {
289
0
            desired_type = IGRAPH_ATTRIBUTE_UNSPECIFIED;
290
0
        }
291
292
6.66k
        IGRAPH_CHECK(igraph_attribute_record_init(&atrec, name, desired_type));
293
6.66k
        IGRAPH_FINALLY(igraph_attribute_record_destroy, &atrec);
294
6.66k
        IGRAPH_CHECK(igraph_attribute_record_list_push_back(attrs, &atrec));
295
6.66k
        IGRAPH_FINALLY_CLEAN(1);  /* ownership of 'atrec' taken by 'attrs' */
296
334k
    } else {
297
        /* already seen, should we update type? */
298
334k
        igraph_attribute_record_t *atrec = igraph_attribute_record_list_get_ptr(attrs, trieid);
299
334k
        igraph_attribute_type_t existing_type = atrec->type;
300
334k
        if (type == IGRAPH_I_GML_TREE_STRING) {
301
249k
            if (existing_type != IGRAPH_ATTRIBUTE_STRING) {
302
21
                IGRAPH_CHECK(igraph_attribute_record_set_type(atrec, IGRAPH_ATTRIBUTE_STRING));
303
21
            }
304
249k
        } else if (existing_type == IGRAPH_ATTRIBUTE_UNSPECIFIED) {
305
0
            if (type == IGRAPH_I_GML_TREE_INTEGER || type == IGRAPH_I_GML_TREE_REAL) {
306
0
                IGRAPH_CHECK(igraph_attribute_record_set_type(atrec, IGRAPH_ATTRIBUTE_NUMERIC));
307
0
            }
308
0
        }
309
334k
    }
310
311
341k
    return IGRAPH_SUCCESS;
312
341k
}
313
314
/* Allocates the contents of attribute records stored in 'attrs'.
315
 * 'no_of_items' is the length of attribute vectors, i.e. no_of_nodes,
316
 * no_of_edges, or 1 for vertex, edge and graph attributes.
317
 * The 'kind' parameter can be "vertex", "edge" or "graph", and
318
 * is used solely for showing better warning messages. */
319
static igraph_error_t allocate_attributes(
320
    igraph_attribute_record_list_t *attrs, igraph_int_t no_of_items,
321
    const char *kind
322
10.0k
) {
323
10.0k
    igraph_int_t i, n = igraph_attribute_record_list_size(attrs);
324
16.6k
    for (i = 0; i < n; i++) {
325
6.66k
        igraph_attribute_record_t *atrec = igraph_attribute_record_list_get_ptr(attrs, i);
326
327
        /* We have unspecified attribute types in the attribute record list at
328
         * this point because we need to keep the same order in the attribute
329
         * record list as it was in the trie that we use to look up an
330
         * attribute record by name. However, we cannot resize unknown attributes
331
         * so we need to take care of this */
332
6.66k
        if (atrec->type != IGRAPH_ATTRIBUTE_UNSPECIFIED) {
333
6.66k
            IGRAPH_CHECK(igraph_attribute_record_resize(atrec, no_of_items));
334
6.66k
        } else {
335
0
            IGRAPH_WARNINGF("Composite %s attribute '%s' ignored in GML file.", kind, atrec->name);
336
0
        }
337
6.66k
    }
338
10.0k
    return IGRAPH_SUCCESS;
339
10.0k
}
340
341
/**
342
 * \function igraph_read_graph_gml
343
 * \brief Read a graph in GML format.
344
 *
345
 * GML is a simple textual format, see
346
 * https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297%26L=1
347
 * for details.
348
 *
349
 * </para><para>
350
 * Although all syntactically correct GML can be parsed,
351
 * we implement only a subset of this format. Some attributes might be
352
 * ignored. Here is a list of all the differences:
353
 * \olist
354
 * \oli Only attributes with a simple type are used: integer, real or
355
 *      string. If an attribute is composite, i.e. an array or a record,
356
 *      then it is ignored. When some values of the attribute are simple and
357
 *      some compound, the composite ones are replaced with a default value
358
 *      (NaN for numeric, <code>""</code> for string).
359
 * \oli <code>comment</code> fields are not ignored. They are treated as any
360
 *      other field and converted to attributes.
361
 * \oli Top level attributes except for <code>Version</code> and the
362
 *      first <code>graph</code> attribute are completely ignored.
363
 * \oli There is no maximum line length or maximum keyword length.
364
 * \oli Only the \c quot, \c amp, \c apos, \c lt and \c gt character entities
365
 *      are supported. Any other entity is passed through unchanged by the reader
366
 *      after issuing a warning, and is expected to be decoded by the user.
367
 * \oli We allow <code>inf</code>, <code>-inf</code> and <code>nan</code>
368
 *      (not a number) as a real number. This is case insensitive, so
369
 *      <code>nan</code>, <code>NaN</code> and <code>NAN</code> are equivalent.
370
 * \endolist
371
 *
372
 * </para><para> Please contact us if you cannot live with these
373
 * limitations of the GML parser.
374
 *
375
 * \param graph Pointer to an uninitialized graph object.
376
 * \param instream The stream to read the GML file from.
377
 * \return Error code.
378
 *
379
 * Time complexity: should be proportional to the length of the file.
380
 *
381
 * \sa \ref igraph_read_graph_graphml() for a more modern format,
382
 * \ref igraph_write_graph_gml() for writing GML files.
383
 *
384
 * \example examples/simple/gml.c
385
 */
386
3.33k
igraph_error_t igraph_read_graph_gml(igraph_t *graph, FILE *instream) {
387
388
3.33k
    igraph_int_t i;
389
3.33k
    igraph_int_t no_of_nodes = 0, no_of_edges = 0;
390
3.33k
    igraph_int_t node_no;
391
3.33k
    igraph_trie_t trie;
392
3.33k
    igraph_vector_int_t edges;
393
3.33k
    igraph_bool_t directed = IGRAPH_UNDIRECTED;
394
3.33k
    igraph_bool_t has_directed = false;
395
3.33k
    igraph_gml_tree_t *gtree;
396
3.33k
    igraph_int_t gidx;
397
3.33k
    igraph_trie_t vattrnames;
398
3.33k
    igraph_trie_t eattrnames;
399
3.33k
    igraph_trie_t gattrnames;
400
3.33k
    igraph_attribute_record_list_t gattrs, vattrs, eattrs;
401
3.33k
    igraph_int_t edgeptr = 0;
402
3.33k
    igraph_i_gml_parsedata_t context;
403
3.33k
    igraph_bool_t entity_warned = false; /* used to warn at most once about unsupported entities */
404
405
3.33k
    IGRAPH_CHECK(igraph_i_gml_parsedata_init(&context));
406
3.33k
    IGRAPH_FINALLY(igraph_i_gml_parsedata_destroy, &context);
407
408
3.33k
    igraph_gml_yylex_init_extra(&context, &context.scanner);
409
410
3.33k
    igraph_gml_yyset_in(instream, context.scanner);
411
412
    /* Protect 'context' from being destroyed before returning from yyparse() */
413
3.33k
    IGRAPH_FINALLY_ENTER();
414
3.33k
    int err = igraph_gml_yyparse(&context);
415
3.33k
    IGRAPH_FINALLY_EXIT();
416
3.33k
    switch (err) {
417
3.33k
    case 0: /* success */
418
3.33k
        break;
419
0
    case 1: /* parse error */
420
0
        if (context.errmsg[0] != '\0') {
421
0
            IGRAPH_ERROR(context.errmsg, IGRAPH_PARSEERROR);
422
0
        } else if (context.igraph_errno != IGRAPH_SUCCESS) {
423
0
            IGRAPH_ERROR("", context.igraph_errno);
424
0
        } else {
425
0
            IGRAPH_ERROR("Cannot read GML file.", IGRAPH_PARSEERROR);
426
0
        }
427
0
        break;
428
0
    case 2: /* out of memory */
429
0
        IGRAPH_ERROR("Cannot read GML file.", IGRAPH_ENOMEM); /* LCOV_EXCL_LINE */
430
0
        break;
431
0
    default: /* must never reach here */
432
        /* Hint: This will usually be triggered if an IGRAPH_CHECK() is used in a Bison
433
         * action instead of an IGRAPH_YY_CHECK(), resulting in an igraph errno being
434
         * returned in place of a Bison error code.
435
         * TODO: What if future Bison versions introduce error codes other than 0, 1 and 2?
436
         */
437
0
        IGRAPH_FATALF("Parser returned unexpected error code (%d) when reading GML file.", err);  /* LCOV_EXCL_LINE */
438
3.33k
    }
439
440
    /* Check version, if present, integer and not '1' then ignored */
441
3.33k
    i = igraph_gml_tree_find(context.tree, "Version", 0);
442
3.33k
    if (i >= 0 &&
443
3.33k
        igraph_gml_tree_type(context.tree, i) == IGRAPH_I_GML_TREE_INTEGER &&
444
3.33k
        igraph_gml_tree_get_integer(context.tree, i) != 1) {
445
0
        IGRAPH_WARNINGF("Unknown GML version: %" IGRAPH_PRId ". "
446
0
                        "Parsing will continue assuming GML version 1, but may fail.",
447
0
                        igraph_gml_tree_get_integer(context.tree, i));
448
0
    }
449
450
    /* Get the graph */
451
3.33k
    gidx = igraph_gml_tree_find(context.tree, "graph", 0);
452
3.33k
    if (gidx == -1) {
453
0
        IGRAPH_ERROR("No 'graph' object in GML file.", IGRAPH_PARSEERROR);
454
0
    }
455
3.33k
    if (igraph_gml_tree_type(context.tree, gidx) !=
456
3.33k
        IGRAPH_I_GML_TREE_TREE) {
457
0
        IGRAPH_ERRORF("Invalid type for 'graph' object in GML file, line %" IGRAPH_PRId ".", IGRAPH_PARSEERROR,
458
0
                      igraph_gml_tree_line(context.tree, gidx));
459
0
    }
460
3.33k
    gtree = igraph_gml_tree_get_tree(context.tree, gidx);
461
462
3.33k
    IGRAPH_CHECK(igraph_attribute_record_list_init(&gattrs, 0));
463
3.33k
    IGRAPH_FINALLY(igraph_attribute_record_list_destroy, &gattrs);
464
3.33k
    IGRAPH_CHECK(igraph_attribute_record_list_init(&vattrs, 0));
465
3.33k
    IGRAPH_FINALLY(igraph_attribute_record_list_destroy, &vattrs);
466
3.33k
    IGRAPH_CHECK(igraph_attribute_record_list_init(&eattrs, 0));
467
3.33k
    IGRAPH_FINALLY(igraph_attribute_record_list_destroy, &eattrs);
468
469
3.33k
    IGRAPH_TRIE_INIT_FINALLY(&trie, 0);
470
3.33k
    IGRAPH_TRIE_INIT_FINALLY(&vattrnames, 0);
471
3.33k
    IGRAPH_TRIE_INIT_FINALLY(&eattrnames, 0);
472
3.33k
    IGRAPH_TRIE_INIT_FINALLY(&gattrnames, 0);
473
474
    /* Now we go over all objects in the graph to
475
     *  - collect the attribute names and types
476
     *  - collect node IDs
477
     *  - set directedness
478
     *  - do some checks which the following code relies on
479
     *
480
     * The 'id' fields of 'node' objects are converted into strings, so that they
481
     * can be inserted into a trie and re-encoded as consecutive integers starting
482
     * at 0. The GML spec allows isolated nodes with no 'id' field. These get a
483
     * generated string id of the form "n123" consisting of "n" and their count
484
     * (i.e. ordinal position) within the GML file.
485
     *
486
     * We use an attribute type value of IGRAPH_ATTRIBUTE_UNSPECIFIED to mark attribute
487
     * records which correspond to composite GML values and must therefore be removed
488
     * before creating the graph.
489
     */
490
3.33k
    node_no = 0;
491
390k
    for (i = 0; i < igraph_gml_tree_length(gtree); i++) {
492
387k
        const char *name = igraph_gml_tree_name(gtree, i);
493
387k
        if (!strcmp(name, "node")) {
494
34.7k
            igraph_gml_tree_t *node;
495
34.7k
            igraph_bool_t hasid;
496
34.7k
            node_no++;
497
34.7k
            no_of_nodes++;
498
34.7k
            if (igraph_gml_tree_type(gtree, i) != IGRAPH_I_GML_TREE_TREE) {
499
0
                IGRAPH_ERRORF("'node' is not a list in GML file, line %" IGRAPH_PRId ".", IGRAPH_PARSEERROR,
500
0
                              igraph_gml_tree_line(gtree, i));
501
0
            }
502
34.7k
            node = igraph_gml_tree_get_tree(gtree, i);
503
34.7k
            hasid = false;
504
93.0k
            for (igraph_int_t j = 0; j < igraph_gml_tree_length(node); j++) {
505
58.3k
                const char *name = igraph_gml_tree_name(node, j);
506
58.3k
                igraph_i_gml_tree_type_t type = igraph_gml_tree_type(node, j);
507
58.3k
                IGRAPH_CHECK(create_or_update_attribute(name, type, &vattrnames, &vattrs));
508
                /* check id */
509
58.3k
                if (!strcmp(name, "id")) {
510
34.7k
                    igraph_int_t id, trie_id;
511
34.7k
                    igraph_int_t trie_size = igraph_trie_size(&trie);
512
34.7k
                    if (hasid) {
513
                        /* A 'node' must not have more than one 'id' field.
514
                         * This error cannot be relaxed into a warning because all ids we find are
515
                         * added to the trie, and eventually converted to igraph vertex ids. */
516
0
                        IGRAPH_ERRORF("Node has multiple 'id' fields in GML file, line %" IGRAPH_PRId ".",
517
0
                                      IGRAPH_PARSEERROR,
518
0
                                      igraph_gml_tree_line(node, j));
519
0
                    }
520
34.7k
                    if (type != IGRAPH_I_GML_TREE_INTEGER) {
521
0
                        IGRAPH_ERRORF("Non-integer node ID in GML file, line %" IGRAPH_PRId ".", IGRAPH_PARSEERROR,
522
0
                                      igraph_gml_tree_line(node, j));
523
0
                    }
524
34.7k
                    id = igraph_gml_tree_get_integer(node, j);
525
34.7k
                    IGRAPH_CHECK(igraph_trie_get(&trie, strid(id, ""), &trie_id));
526
34.7k
                    if (trie_id != trie_size) {
527
                        /* This id has already been seen in a previous node. */
528
0
                        IGRAPH_ERRORF("Duplicate node ID in GML file, line %" IGRAPH_PRId ".", IGRAPH_PARSEERROR,
529
0
                                      igraph_gml_tree_line(node, j));
530
0
                    }
531
34.7k
                    hasid = true;
532
34.7k
                }
533
58.3k
            }
534
34.7k
            if (!hasid) {
535
                /* Isolated nodes are allowed not to have an id.
536
                 * We generate an "n"-prefixed string id to be used in the trie. */
537
0
                igraph_int_t trie_id;
538
0
                IGRAPH_CHECK(igraph_trie_get(&trie, strid(node_no, "n"), &trie_id));
539
0
            }
540
352k
        } else if (!strcmp(name, "edge")) {
541
348k
            igraph_gml_tree_t *edge;
542
348k
            igraph_bool_t has_source = false, has_target = false;
543
348k
            no_of_edges++;
544
348k
            if (igraph_gml_tree_type(gtree, i) != IGRAPH_I_GML_TREE_TREE) {
545
0
                IGRAPH_ERRORF("'edge' is not a list in GML file, line %" IGRAPH_PRId ".", IGRAPH_PARSEERROR,
546
0
                              igraph_gml_tree_line(gtree, i));
547
0
            }
548
348k
            edge = igraph_gml_tree_get_tree(gtree, i);
549
1.32M
            for (igraph_int_t j = 0; j < igraph_gml_tree_length(edge); j++) {
550
978k
                const char *name = igraph_gml_tree_name(edge, j);
551
978k
                igraph_i_gml_tree_type_t type = igraph_gml_tree_type(edge, j);
552
978k
                if (!strcmp(name, "source")) {
553
348k
                    if (has_source) {
554
                        /* An edge must not have more than one 'source' field.
555
                         * This could be relaxed to a warning, but we keep it as an error
556
                         * for consistency with the handling of duplicate node 'id' field,
557
                         * and because it indicates a serious corruption in the GML file. */
558
0
                        IGRAPH_ERRORF("Duplicate 'source' in an edge in GML file, line %" IGRAPH_PRId ".",
559
0
                                      IGRAPH_PARSEERROR,
560
0
                                      igraph_gml_tree_line(edge, j));
561
0
                    }
562
348k
                    has_source = true;
563
348k
                    if (type != IGRAPH_I_GML_TREE_INTEGER) {
564
0
                        IGRAPH_ERRORF("Non-integer 'source' for an edge in GML file, line %" IGRAPH_PRId ".",
565
0
                                      IGRAPH_PARSEERROR,
566
0
                                      igraph_gml_tree_line(edge, j));
567
0
                    }
568
630k
                } else if (!strcmp(name, "target")) {
569
348k
                    if (has_target) {
570
                        /* An edge must not have more than one 'target' field. */
571
0
                        IGRAPH_ERRORF("Duplicate 'target' in an edge in GML file, line %" IGRAPH_PRId ".",
572
0
                                      IGRAPH_PARSEERROR,
573
0
                                      igraph_gml_tree_line(edge, j));
574
0
                    }
575
348k
                    has_target = true;
576
348k
                    if (type != IGRAPH_I_GML_TREE_INTEGER) {
577
0
                        IGRAPH_ERRORF("Non-integer 'target' for an edge in GML file, line %" IGRAPH_PRId ".",
578
0
                                      IGRAPH_PARSEERROR,
579
0
                                      igraph_gml_tree_line(edge, j));
580
0
                    }
581
348k
                } else {
582
282k
                    IGRAPH_CHECK(create_or_update_attribute(name, type, &eattrnames, &eattrs));
583
282k
                }
584
978k
            } /* for */
585
348k
            if (!has_source) {
586
0
                IGRAPH_ERRORF("No 'source' for edge in GML file, line %" IGRAPH_PRId ".", IGRAPH_PARSEERROR,
587
0
                              igraph_gml_tree_line(gtree, i));
588
0
            }
589
348k
            if (!has_target) {
590
0
                IGRAPH_ERRORF("No 'target' for edge in GML file, line %" IGRAPH_PRId ".", IGRAPH_PARSEERROR,
591
0
                              igraph_gml_tree_line(gtree, i));
592
0
            }
593
348k
        } else if (! strcmp(name, "directed")) {
594
            /* Set directedness of graph. */
595
3.33k
            if (has_directed) {
596
                /* Be tolerant of duplicate entries, but do show a warning. */
597
0
                IGRAPH_WARNINGF("Duplicate 'directed' field in 'graph', line %" IGRAPH_PRId ". "
598
0
                                "Ignoring previous 'directed' fields.",
599
0
                                igraph_gml_tree_line(gtree, i));
600
0
            }
601
3.33k
            if (igraph_gml_tree_type(gtree, i) == IGRAPH_I_GML_TREE_INTEGER) {
602
3.33k
                igraph_int_t dir = igraph_gml_tree_get_integer(gtree, i);
603
3.33k
                if (dir != 0 && dir != 1) {
604
0
                    IGRAPH_WARNINGF(
605
0
                        "Invalid value %" IGRAPH_PRId " for 'directed' attribute on line %" IGRAPH_PRId ", should be 0 or 1.",
606
0
                        dir, igraph_gml_tree_line(gtree, i));
607
0
                }
608
3.33k
                if (dir) {
609
139
                    directed = IGRAPH_DIRECTED;
610
139
                }
611
3.33k
                has_directed = true;
612
3.33k
            } else {
613
0
                IGRAPH_WARNINGF("Invalid type for 'directed' attribute on line %" IGRAPH_PRId ", assuming undirected.",
614
0
                                igraph_gml_tree_line(gtree, i));
615
0
            }
616
3.33k
        } else {
617
            /* Add the rest of items as graph attributes. */
618
717
            igraph_i_gml_tree_type_t type = igraph_gml_tree_type(gtree, i);
619
717
            IGRAPH_CHECK(create_or_update_attribute(name, type, &gattrnames, &gattrs));
620
717
        }
621
387k
    }
622
623
    /* At this point, all nodes must have an id (from the file or generated) stored
624
     * in the trie. Any condition that violates this should have been caught during
625
     * the preceding checks. */
626
3.33k
    IGRAPH_ASSERT(igraph_trie_size(&trie) == no_of_nodes);
627
628
    /* Now we allocate the vectors and strvectors for the attributes */
629
3.33k
    IGRAPH_CHECK(allocate_attributes(&vattrs, no_of_nodes, "vertex"));
630
3.33k
    IGRAPH_CHECK(allocate_attributes(&eattrs, no_of_edges, "edge"));
631
3.33k
    IGRAPH_CHECK(allocate_attributes(&gattrs, 1, "graph"));
632
633
    /* Add edges, edge attributes and vertex attributes */
634
3.33k
    IGRAPH_VECTOR_INT_INIT_FINALLY(&edges, no_of_edges * 2);
635
3.33k
    node_no = 0;
636
390k
    for (i = 0; i < igraph_gml_tree_length(gtree); i++) {
637
387k
        const char *name;
638
387k
        name = igraph_gml_tree_name(gtree, i);
639
387k
        if (!strcmp(name, "node")) {
640
34.7k
            igraph_gml_tree_t *node = igraph_gml_tree_get_tree(gtree, i);
641
34.7k
            igraph_int_t iidx = igraph_gml_tree_find(node, "id", 0);
642
34.7k
            igraph_int_t trie_id;
643
34.7k
            const char *sid;
644
34.7k
            node_no++;
645
34.7k
            if (iidx < 0) {
646
                /* Isolated node with no id field, use n-prefixed generated id */
647
0
                sid = strid(node_no, "n");
648
34.7k
            } else {
649
34.7k
                sid = strid(igraph_gml_tree_get_integer(node, iidx), "");
650
34.7k
            }
651
34.7k
            IGRAPH_CHECK(igraph_trie_get(&trie, sid, &trie_id));
652
93.0k
            for (igraph_int_t j = 0; j < igraph_gml_tree_length(node); j++) {
653
58.3k
                const char *aname = igraph_gml_tree_name(node, j);
654
58.3k
                igraph_attribute_record_t *atrec;
655
58.3k
                igraph_attribute_type_t type;
656
58.3k
                igraph_int_t ai;
657
58.3k
                IGRAPH_CHECK(igraph_trie_get(&vattrnames, aname, &ai));
658
58.3k
                atrec = igraph_attribute_record_list_get_ptr(&vattrs, ai);
659
58.3k
                type = atrec->type;
660
58.3k
                if (type == IGRAPH_ATTRIBUTE_NUMERIC) {
661
44.6k
                    VECTOR(*atrec->value.as_vector)[trie_id] = igraph_i_gml_toreal(node, j);
662
44.6k
                } else if (type == IGRAPH_ATTRIBUTE_STRING) {
663
13.6k
                    igraph_strvector_t *v = atrec->value.as_strvector;
664
13.6k
                    const char *value = igraph_i_gml_tostring(node, j);
665
13.6k
                    if (needs_coding(value)) {
666
7.69k
                        char *value_decoded;
667
7.69k
                        IGRAPH_CHECK(entity_decode(value, &value_decoded, &entity_warned));
668
7.69k
                        IGRAPH_FINALLY(igraph_free, value_decoded);
669
7.69k
                        IGRAPH_CHECK(igraph_strvector_set(v, trie_id, value_decoded));
670
7.69k
                        IGRAPH_FREE(value_decoded);
671
7.69k
                        IGRAPH_FINALLY_CLEAN(1);
672
7.69k
                    } else {
673
5.98k
                        IGRAPH_CHECK(igraph_strvector_set(v, trie_id, value));
674
5.98k
                    }
675
13.6k
                } else {
676
                    /* Ignored composite attribute */
677
0
                }
678
58.3k
            }
679
352k
        } else if (!strcmp(name, "edge")) {
680
348k
            igraph_gml_tree_t *edge;
681
348k
            igraph_int_t from, to, fromidx = 0, toidx = 0;
682
348k
            edge = igraph_gml_tree_get_tree(gtree, i);
683
1.32M
            for (igraph_int_t j = 0; j < igraph_gml_tree_length(edge); j++) {
684
978k
                const char *aname = igraph_gml_tree_name(edge, j);
685
978k
                if (!strcmp(aname, "source")) {
686
348k
                    fromidx = igraph_gml_tree_find(edge, "source", 0);
687
630k
                } else if (!strcmp(aname, "target")) {
688
348k
                    toidx = igraph_gml_tree_find(edge, "target", 0);
689
348k
                } else {
690
282k
                    igraph_int_t edgeid = edgeptr / 2;
691
282k
                    igraph_int_t ai;
692
282k
                    igraph_attribute_record_t *atrec;
693
282k
                    igraph_attribute_type_t type;
694
282k
                    IGRAPH_CHECK(igraph_trie_get(&eattrnames, aname, &ai));
695
282k
                    atrec = igraph_attribute_record_list_get_ptr(&eattrs, ai);
696
282k
                    type = atrec->type;
697
282k
                    if (type == IGRAPH_ATTRIBUTE_NUMERIC) {
698
43.2k
                        VECTOR(*atrec->value.as_vector)[edgeid] = igraph_i_gml_toreal(edge, j);
699
238k
                    } else if (type == IGRAPH_ATTRIBUTE_STRING) {
700
238k
                        igraph_strvector_t *v = atrec->value.as_strvector;
701
238k
                        const char *value = igraph_i_gml_tostring(edge, j);
702
238k
                        if (needs_coding(value)) {
703
1.92k
                            char *value_decoded;
704
1.92k
                            IGRAPH_CHECK(entity_decode(value, &value_decoded, &entity_warned));
705
1.92k
                            IGRAPH_FINALLY(igraph_free, value_decoded);
706
1.92k
                            IGRAPH_CHECK(igraph_strvector_set(v, edgeid, value_decoded));
707
1.92k
                            IGRAPH_FREE(value_decoded);
708
1.92k
                            IGRAPH_FINALLY_CLEAN(1);
709
236k
                        } else {
710
236k
                            IGRAPH_CHECK(igraph_strvector_set(v, edgeid, value));
711
236k
                        }
712
238k
                    } else {
713
                        /* Ignored composite attribute */
714
0
                    }
715
282k
                }
716
978k
            }
717
348k
            from = igraph_gml_tree_get_integer(edge, fromidx);
718
348k
            to = igraph_gml_tree_get_integer(edge, toidx);
719
348k
            IGRAPH_CHECK(igraph_trie_check(&trie, strid(from, ""), &from));
720
348k
            if (from < 0) {
721
0
                IGRAPH_ERRORF("Unknown source node ID found in an edge in GML file, line %" IGRAPH_PRId ".",
722
0
                             IGRAPH_PARSEERROR, igraph_gml_tree_line(edge, fromidx));
723
0
            }
724
348k
            IGRAPH_CHECK(igraph_trie_check(&trie, strid(to, ""), &to));
725
348k
            if (to < 0) {
726
0
                IGRAPH_ERRORF("Unknown target node ID found in an edge in GML file, line %" IGRAPH_PRId ".",
727
0
                             IGRAPH_PARSEERROR, igraph_gml_tree_line(edge, toidx));
728
0
            }
729
348k
            VECTOR(edges)[edgeptr++] = from;
730
348k
            VECTOR(edges)[edgeptr++] = to;
731
348k
        } else if (! strcmp(name, "directed")) {
732
            /* Nothing to do for 'directed' field, already handled earlier. */
733
3.33k
        } else {
734
            /* Set the rest as graph attributes */
735
717
            igraph_int_t ai;
736
717
            igraph_attribute_record_t *atrec;
737
717
            igraph_attribute_type_t type;
738
717
            IGRAPH_CHECK(igraph_trie_get(&gattrnames, name, &ai));
739
717
            atrec = igraph_attribute_record_list_get_ptr(&gattrs, ai);
740
717
            type = atrec->type;
741
717
            if (type == IGRAPH_ATTRIBUTE_NUMERIC) {
742
134
                VECTOR(*atrec->value.as_vector)[0] = igraph_i_gml_toreal(gtree, i);
743
583
            } else if (type == IGRAPH_ATTRIBUTE_STRING) {
744
583
                igraph_strvector_t *v = atrec->value.as_strvector;
745
583
                const char *value = igraph_i_gml_tostring(gtree, i);
746
583
                if (needs_coding(value)) {
747
60
                    char *value_decoded;
748
60
                    IGRAPH_CHECK(entity_decode(value, &value_decoded, &entity_warned));
749
60
                    IGRAPH_FINALLY(igraph_free, value_decoded);
750
60
                    IGRAPH_CHECK(igraph_strvector_set(v, 0, value_decoded));
751
60
                    IGRAPH_FREE(value_decoded);
752
60
                    IGRAPH_FINALLY_CLEAN(1);
753
523
                } else {
754
523
                    IGRAPH_CHECK(igraph_strvector_set(v, 0, value));
755
523
                }
756
583
            } else {
757
                /* Ignored composite attribute */
758
0
            }
759
717
        }
760
387k
    }
761
762
    /* Remove composite attributes that we cannot represent in igraph */
763
3.33k
    IGRAPH_CHECK(prune_unknown_attributes(&vattrs));
764
3.33k
    IGRAPH_CHECK(prune_unknown_attributes(&eattrs));
765
3.33k
    IGRAPH_CHECK(prune_unknown_attributes(&gattrs));
766
767
3.33k
    igraph_trie_destroy(&trie);
768
3.33k
    igraph_trie_destroy(&gattrnames);
769
3.33k
    igraph_trie_destroy(&vattrnames);
770
3.33k
    igraph_trie_destroy(&eattrnames);
771
3.33k
    IGRAPH_FINALLY_CLEAN(4);
772
773
3.33k
    IGRAPH_CHECK(igraph_empty_attrs(graph, 0, directed, &gattrs));
774
3.33k
    IGRAPH_FINALLY(igraph_destroy, graph);
775
3.33k
    IGRAPH_CHECK(igraph_add_vertices(graph, no_of_nodes, &vattrs));
776
3.33k
    IGRAPH_CHECK(igraph_add_edges(graph, &edges, &eattrs));
777
3.33k
    IGRAPH_FINALLY_CLEAN(1); /* do not destroy 'graph', just pop it from the stack */
778
779
3.33k
    igraph_vector_int_destroy(&edges);
780
3.33k
    igraph_attribute_record_list_destroy(&eattrs);
781
3.33k
    igraph_attribute_record_list_destroy(&vattrs);
782
3.33k
    igraph_attribute_record_list_destroy(&gattrs);
783
3.33k
    igraph_i_gml_parsedata_destroy(&context);
784
3.33k
    IGRAPH_FINALLY_CLEAN(5);
785
786
3.33k
    return IGRAPH_SUCCESS;
787
3.33k
}
788
789
350k
static igraph_error_t igraph_i_gml_convert_to_key(const char *orig, char **key) {
790
350k
    char strno[50];
791
350k
    size_t i, len = strlen(orig), newlen = 0, plen = 0;
792
793
    /* do we need a prefix? */
794
350k
    if (len == 0 || !isalpha((unsigned char) orig[0])) {
795
10.9k
        snprintf(strno, sizeof(strno) - 1, "igraph");
796
10.9k
        plen = newlen = strlen(strno);
797
10.9k
    }
798
122M
    for (i = 0; i < len; i++) {
799
121M
        if (isalnum((unsigned char) orig[i])) {
800
17.7M
            newlen++;
801
17.7M
        }
802
121M
    }
803
350k
    *key = IGRAPH_CALLOC(newlen + 1, char);
804
350k
    IGRAPH_CHECK_OOM(*key, "Writing GML format failed.");
805
350k
    memcpy(*key, strno, plen * sizeof(char));
806
122M
    for (i = 0; i < len; i++) {
807
121M
        if (isalnum((unsigned char) orig[i])) {
808
17.7M
            (*key)[plen++] = orig[i];
809
17.7M
        }
810
121M
    }
811
350k
    (*key)[newlen] = '\0';
812
813
350k
    return IGRAPH_SUCCESS;
814
350k
}
815
816
/* Checks if a vector is free of duplicates. Since NaN == NaN is false, duplicate NaN values
817
 * will not be detected. */
818
41
static igraph_error_t igraph_i_vector_is_duplicate_free(const igraph_vector_t *v, igraph_bool_t *res) {
819
41
    igraph_vector_t u;
820
41
    igraph_int_t n = igraph_vector_size(v);
821
822
41
    if (n < 2) {
823
14
        *res = true;
824
14
        return IGRAPH_SUCCESS;
825
14
    }
826
827
27
    IGRAPH_CHECK(igraph_vector_init_copy(&u, v));
828
27
    IGRAPH_FINALLY(igraph_vector_destroy, &u);
829
27
    igraph_vector_sort(&u);
830
831
27
    *res = true;
832
27
    for (igraph_int_t i=1; i < n; i++) {
833
27
        if (VECTOR(u)[i-1] == VECTOR(u)[i]) {
834
27
            *res = false;
835
27
            break;
836
27
        }
837
27
    }
838
839
27
    igraph_vector_destroy(&u);
840
27
    IGRAPH_FINALLY_CLEAN(1);
841
842
27
    return IGRAPH_SUCCESS;
843
27
}
844
845
1.82M
#define CHECK(cmd) do { int ret=cmd; if (ret<0) IGRAPH_ERROR("Writing GML format failed.", IGRAPH_EFILE); } while (0)
846
847
/**
848
 * \function igraph_write_graph_gml
849
 * \brief Write the graph to a stream in GML format.
850
 *
851
 * GML is a quite general textual format, see
852
 * https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297%26L=1
853
 * for details.
854
 *
855
 * </para><para>
856
 * The graph, vertex and edge attributes are written to the
857
 * file as well, if they are numeric or string. Boolean attributes are converted
858
 * to numeric, with 0 and 1 used for false and true, respectively.
859
 * NaN values of numeric attributes are skipped, as NaN is not part of the GML
860
 * specification and other software may not be able to read files containing them.
861
 * This is consistent with \ref igraph_read_graph_gml(), which produces NaN
862
 * when an attribute value is missing. In contrast with NaN, infinite values
863
 * are retained. Ensure that none of the numeric attribute values are infinite
864
 * to produce a conformant GML file that can be read by other software.
865
 *
866
 * </para><para>
867
 * As igraph is more forgiving about attribute names, it might
868
 * be necessary to simplify them before writing to the GML file.
869
 * This way we'll have a syntactically correct GML file. The following
870
 * simple procedure is performed on each attribute name: first the alphanumeric
871
 * characters are extracted, the others are ignored. Then if the first character
872
 * is not a letter then the attribute name is prefixed with <quote>igraph</quote>.
873
 * Note that this might result in identical names for two attributes; igraph
874
 * does not check this.
875
 *
876
 * </para><para>
877
 * The <quote>id</quote> vertex attribute is treated specially.
878
 * If the <parameter>id</parameter> argument is not \c NULL then it should be a numeric
879
 * vector with the vertex IDs and the <quote>id</quote> vertex attribute is
880
 * ignored (if there is one). If <parameter>id</parameter> is \c NULL and there is a
881
 * numeric <quote>id</quote> vertex attribute, it will be used instead. If IDs
882
 * are not specified in either way then the regular igraph vertex IDs are used.
883
 * If some of the supplied ID values are invalid (non-integer or NaN), all supplied
884
 * IDs are ignored and igraph vertex IDs are used instead.
885
 *
886
 * </para><para>
887
 * Note that whichever way vertex IDs are specified, their uniqueness is not checked.
888
 *
889
 * </para><para>
890
 * If the graph has edge attributes that become <quote>source</quote>
891
 * or <quote>target</quote> after encoding, or the graph has an attribute that becomes
892
 * <quote>directed</quote>, they will be ignored with a warning. GML uses these attributes
893
 * to specify the edge endpoints, and the graph directedness, so we cannot write them
894
 * to the file. Rename them before calling this function if you want to preserve them.
895
 *
896
 * \param graph The graph to write to the stream.
897
 * \param outstream The stream to write the file to.
898
 * \param options Set of <code>|</code>-combinable boolean flags for writing the GML file.
899
 *        \clist
900
 *          \cli 0
901
 *               All options turned off.
902
 *          \cli IGRAPH_WRITE_GML_DEFAULT_SW
903
 *               Default options, currently equivalent to 0. May change in future versions.
904
 *          \cli IGRAPH_WRITE_GML_ENCODE_ONLY_QUOT_SW
905
 *               Do not encode any other characters than " as entities. Specifically, this
906
 *               option prevents the encoding of &amp;. Useful when re-exporting a graph
907
 *               that was read from a GML file in which igraph could not interpret all entities,
908
 *               and thus passed them through without decoding.
909
 *        \endclist
910
 * \param id Either <code>NULL</code> or a numeric vector with the vertex IDs.
911
 *        See details above.
912
 * \param creator An optional string to write to the stream in the creator line.
913
 *        If \c NULL, the igraph version with the current date and time is added.
914
 *        If <code>""</code>, the creator line is omitted. Otherwise, the
915
 *        supplied string is used verbatim.
916
 * \return Error code.
917
 *
918
 * Time complexity: should be proportional to the number of characters written
919
 * to the file.
920
 *
921
 * \sa \ref igraph_read_graph_gml() for reading GML files,
922
 * \ref igraph_read_graph_graphml() for a more modern format.
923
 *
924
 * \example examples/simple/gml.c
925
 */
926
927
igraph_error_t igraph_write_graph_gml(const igraph_t *graph, FILE *outstream,
928
                                      igraph_write_gml_sw_t options,
929
3.33k
                                      const igraph_vector_t *id, const char *creator) {
930
3.33k
    igraph_strvector_t gnames, vnames, enames; /* attribute names */
931
3.33k
    igraph_vector_int_t gtypes, vtypes, etypes; /* attribute types */
932
3.33k
    igraph_int_t gattr_no, vattr_no, eattr_no; /* attribute counts */
933
3.33k
    igraph_vector_t numv;
934
3.33k
    igraph_strvector_t strv;
935
3.33k
    igraph_vector_bool_t boolv;
936
3.33k
    igraph_int_t i;
937
3.33k
    igraph_int_t no_of_nodes = igraph_vcount(graph);
938
3.33k
    igraph_int_t no_of_edges = igraph_ecount(graph);
939
940
    /* Each element is a bit field used to prevent showing more
941
     * than one warning for each vertex or edge attribute. */
942
3.33k
    igraph_vector_int_t warning_shown;
943
944
3.33k
    igraph_vector_t v_myid;
945
3.33k
    const igraph_vector_t *myid = id;
946
947
    /* Creator line */
948
3.33k
    if (creator == NULL) {
949
0
        time_t curtime = time(0);
950
0
        char *timestr = ctime(&curtime);
951
0
        timestr[strlen(timestr) - 1] = '\0'; /* nicely remove \n */
952
953
0
        CHECK(fprintf(outstream,
954
0
                      "Creator \"igraph version %s %s\"\n",
955
0
                      IGRAPH_VERSION, timestr));
956
3.33k
    } else if (creator[0] == '\0') {
957
        /* creator == "", omit Creator line */
958
3.33k
    } else {
959
3.33k
        if (needs_coding(creator)) {
960
0
            char *d;
961
0
            IGRAPH_CHECK(entity_encode(creator, &d, IGRAPH_WRITE_GML_ENCODE_ONLY_QUOT_SW & options));
962
0
            IGRAPH_FINALLY(igraph_free, d);
963
0
            CHECK(fprintf(outstream,
964
0
                          "Creator \"%s\"\n",
965
0
                          creator));
966
0
            IGRAPH_FREE(d);
967
0
            IGRAPH_FINALLY_CLEAN(1);
968
3.33k
        } else {
969
3.33k
            CHECK(fprintf(outstream,
970
3.33k
                          "Creator \"%s\"\n",
971
3.33k
                          creator));
972
3.33k
        }
973
3.33k
    }
974
975
    /* Version line */
976
3.33k
    CHECK(fprintf(outstream, "Version 1\n"));
977
978
    /* The graph */
979
3.33k
    CHECK(fprintf(outstream, "graph\n[\n"));
980
981
3.33k
    IGRAPH_STRVECTOR_INIT_FINALLY(&gnames, 0);
982
3.33k
    IGRAPH_STRVECTOR_INIT_FINALLY(&vnames, 0);
983
3.33k
    IGRAPH_STRVECTOR_INIT_FINALLY(&enames, 0);
984
3.33k
    IGRAPH_VECTOR_INT_INIT_FINALLY(&gtypes, 0);
985
3.33k
    IGRAPH_VECTOR_INT_INIT_FINALLY(&vtypes, 0);
986
3.33k
    IGRAPH_VECTOR_INT_INIT_FINALLY(&etypes, 0);
987
3.33k
    IGRAPH_CHECK(igraph_i_attribute_get_info(graph,
988
3.33k
                 &gnames, &gtypes,
989
3.33k
                 &vnames, &vtypes,
990
3.33k
                 &enames, &etypes));
991
3.33k
    gattr_no = igraph_vector_int_size(&gtypes);
992
3.33k
    vattr_no = igraph_vector_int_size(&vtypes);
993
3.33k
    eattr_no = igraph_vector_int_size(&etypes);
994
995
3.33k
    IGRAPH_VECTOR_INIT_FINALLY(&numv, 1);
996
3.33k
    IGRAPH_STRVECTOR_INIT_FINALLY(&strv, 1);
997
3.33k
    IGRAPH_VECTOR_BOOL_INIT_FINALLY(&boolv, 1);
998
999
    /* Check whether there is an 'id' node attribute if the supplied is 0 */
1000
3.33k
    if (!id) {
1001
3.33k
        igraph_bool_t found = false;
1002
8.55k
        for (i = 0; i < igraph_vector_int_size(&vtypes); i++) {
1003
5.26k
            const char *n = igraph_strvector_get(&vnames, i);
1004
5.26k
            if (!strcmp(n, "id") && VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) {
1005
43
                found = true; break;
1006
43
            }
1007
5.26k
        }
1008
3.33k
        if (found) {
1009
43
            IGRAPH_VECTOR_INIT_FINALLY(&v_myid, no_of_nodes);
1010
43
            IGRAPH_CHECK(igraph_i_attribute_get_numeric_vertex_attr(graph, "id",
1011
43
                         igraph_vss_all(),
1012
43
                         &v_myid));
1013
43
            myid = &v_myid;
1014
43
        }
1015
3.33k
    }
1016
1017
    /* Scan id vector for invalid values. If any are found, all ids are ignored.
1018
     * Invalid values may occur as a result of reading a GML file in which some
1019
     * nodes did not have an id, or by adding new vertices to a graph with an "id"
1020
     * attribute. In this case, the "id" attribute will contain NaN values.
1021
     */
1022
3.33k
    if (myid) {
1023
43
        if (igraph_vector_size(myid) != no_of_nodes) {
1024
0
            IGRAPH_ERROR("Size of ID vector must match vertex count.", IGRAPH_EINVAL);
1025
0
        }
1026
1.36k
        for (i = 0; i < no_of_nodes; ++i) {
1027
1.32k
            igraph_real_t val = VECTOR(*myid)[i];
1028
1.32k
            igraph_real_t trunc_val = trunc(val);
1029
1.32k
            if (! (val == trunc_val && igraph_i_is_real_representable_as_integer(trunc_val))) {
1030
2
                IGRAPH_WARNINGF("%g is not a valid integer ID for GML files, ignoring all supplied IDs.", val);
1031
2
                if (myid == &v_myid) {
1032
2
                    igraph_vector_destroy(&v_myid);
1033
2
                    IGRAPH_FINALLY_CLEAN(1);
1034
2
                }
1035
2
                myid = NULL;
1036
2
                break;
1037
2
            }
1038
1.32k
        }
1039
43
    }
1040
1041
3.33k
    if (myid) {
1042
41
        igraph_bool_t duplicate_free;
1043
41
        IGRAPH_CHECK(igraph_i_vector_is_duplicate_free(myid, &duplicate_free));
1044
41
        if (! duplicate_free) {
1045
27
            IGRAPH_WARNING("Duplicate ID values found, ignoring supplied IDs.");
1046
27
            if (myid == &v_myid) {
1047
27
                igraph_vector_destroy(&v_myid);
1048
27
                IGRAPH_FINALLY_CLEAN(1);
1049
27
            }
1050
27
            myid = NULL;
1051
27
        }
1052
41
    }
1053
1054
    /* directedness */
1055
3.33k
    CHECK(fprintf(outstream, "  directed %i\n", igraph_is_directed(graph) ? 1 : 0));
1056
1057
    /* Graph attributes first */
1058
4.13k
    for (i = 0; i < gattr_no; i++) {
1059
800
        const char *name;
1060
800
        char *newname;
1061
800
        name = igraph_strvector_get(&gnames, i);
1062
800
        IGRAPH_CHECK(igraph_i_gml_convert_to_key(name, &newname));
1063
800
        IGRAPH_FINALLY(igraph_free, newname);
1064
800
        if (!strcmp(newname, "directed")|| !strcmp(newname, "edge") || !strcmp(newname, "node")) {
1065
20
            IGRAPH_WARNINGF("The graph attribute '%s' was ignored while writing GML format.", name);
1066
780
        } else {
1067
780
            if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) {
1068
75
                IGRAPH_CHECK(igraph_i_attribute_get_numeric_graph_attr(graph, name, &numv));
1069
                /* Treat NaN as missing, skip writing it. GML does not officially support NaN. */
1070
75
                if (! isnan(VECTOR(numv)[0])) {
1071
12
                    if (! isfinite(VECTOR(numv)[0])) {
1072
0
                        IGRAPH_WARNINGF("Infinite value in numeric graph attribute '%s'. "
1073
0
                                        "Produced GML file will not be conformant.", name);
1074
0
                    }
1075
12
                    CHECK(fprintf(outstream, "  %s ", newname));
1076
12
                    CHECK(igraph_real_fprintf_precise(outstream, VECTOR(numv)[0]));
1077
12
                    CHECK(fputc('\n', outstream));
1078
12
                }
1079
705
            } else if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_STRING) {
1080
568
                const char *s;
1081
568
                IGRAPH_CHECK(igraph_i_attribute_get_string_graph_attr(graph, name, &strv));
1082
568
                s = igraph_strvector_get(&strv, 0);
1083
568
                if (needs_coding(s)) {
1084
60
                    char *d;
1085
60
                    IGRAPH_CHECK(entity_encode(s, &d, IGRAPH_WRITE_GML_ENCODE_ONLY_QUOT_SW & options));
1086
60
                    IGRAPH_FINALLY(igraph_free, d);
1087
60
                    CHECK(fprintf(outstream, "  %s \"%s\"\n", newname, d));
1088
60
                    IGRAPH_FREE(d);
1089
60
                    IGRAPH_FINALLY_CLEAN(1);
1090
508
                } else {
1091
508
                    CHECK(fprintf(outstream, "  %s \"%s\"\n", newname, s));
1092
508
                }
1093
568
            } else if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_BOOLEAN) {
1094
137
                IGRAPH_CHECK(igraph_i_attribute_get_bool_graph_attr(graph, name, &boolv));
1095
137
                CHECK(fprintf(outstream, "  %s %d\n", newname, VECTOR(boolv)[0] ? 1 : 0));
1096
137
                IGRAPH_WARNING("A boolean graph attribute was converted to numeric.");
1097
137
            } else {
1098
0
                IGRAPH_WARNING("A non-numeric, non-string, non-boolean graph attribute ignored.");
1099
0
            }
1100
780
        }
1101
800
        IGRAPH_FREE(newname);
1102
800
        IGRAPH_FINALLY_CLEAN(1);
1103
800
    }
1104
1105
    /* Macros used to work with the bit fiels in 'warning_shown',
1106
     * and avoid showing warnings more than once for each attribute. */
1107
50.7k
#define GETBIT(k, i) ((k) & (1 << i))
1108
3.33k
#define SETBIT(k, i) ((k) |= (1 << i))
1109
3.33k
#define WARN_ONCE(attrno, bit, warn) \
1110
50.7k
    do { \
1111
50.7k
        igraph_int_t *p = &VECTOR(warning_shown)[attrno]; \
1112
50.7k
        if (! GETBIT(*p, bit)) { \
1113
2.03k
            warn; \
1114
1.01k
            SETBIT(*p, bit); \
1115
1.01k
        } \
1116
50.7k
    } while (0)
1117
1118
1119
    /* Now come the vertices */
1120
3.33k
    IGRAPH_VECTOR_INT_INIT_FINALLY(&warning_shown, vattr_no);
1121
38.0k
    for (i = 0; i < no_of_nodes; i++) {
1122
34.7k
        igraph_int_t j;
1123
34.7k
        CHECK(fprintf(outstream, "  node\n  [\n"));
1124
        /* id */
1125
34.7k
        CHECK(fprintf(outstream, "    id %" IGRAPH_PRId "\n", myid ? (igraph_int_t)VECTOR(*myid)[i] : i));
1126
        /* other attributes */
1127
94.2k
        for (j = 0; j < vattr_no; j++) {
1128
59.5k
            igraph_attribute_type_t type = (igraph_attribute_type_t) VECTOR(vtypes)[j];
1129
59.5k
            const char *name;
1130
59.5k
            char *newname;
1131
59.5k
            name = igraph_strvector_get(&vnames, j);
1132
59.5k
            if (!strcmp(name, "id")) {
1133
                /* No warning, the presence of this attribute is expected, and is handled specially. */
1134
34.4k
                continue;
1135
34.4k
            }
1136
25.1k
            IGRAPH_CHECK(igraph_i_gml_convert_to_key(name, &newname));
1137
25.1k
            IGRAPH_FINALLY(igraph_free, newname);
1138
25.1k
            if (!strcmp(newname, "id")) {
1139
                /* In case an attribute name would conflict with 'id' only after encoding. */
1140
337
                WARN_ONCE(j, 0,
1141
337
                          IGRAPH_WARNINGF("The vertex attribute '%s' was ignored while writing GML format.", name));
1142
24.7k
            } else {
1143
24.7k
                if (type == IGRAPH_ATTRIBUTE_NUMERIC) {
1144
3.68k
                    IGRAPH_CHECK(igraph_i_attribute_get_numeric_vertex_attr(graph, name,
1145
3.68k
                                 igraph_vss_1(i), &numv));
1146
                    /* Treat NaN as missing, skip writing it. GML does not officially support NaN. */
1147
3.68k
                    if (! isnan(VECTOR(numv)[0])) {
1148
2.55k
                        if (! isfinite(VECTOR(numv)[0])) {
1149
0
                            WARN_ONCE(j, 3,
1150
0
                                      IGRAPH_WARNINGF("Infinite value in numeric vertex attribute '%s'. "
1151
0
                                                      "Produced GML file will not be conformant.", name));
1152
0
                        }
1153
2.55k
                        CHECK(fprintf(outstream, "    %s ", newname));
1154
2.55k
                        CHECK(igraph_real_fprintf_precise(outstream, VECTOR(numv)[0]));
1155
2.55k
                        CHECK(fputc('\n', outstream));
1156
2.55k
                    }
1157
21.1k
                } else if (type == IGRAPH_ATTRIBUTE_STRING) {
1158
13.6k
                    const char *s;
1159
13.6k
                    IGRAPH_CHECK(igraph_i_attribute_get_string_vertex_attr(graph, name,
1160
13.6k
                                 igraph_vss_1(i), &strv));
1161
13.6k
                    s = igraph_strvector_get(&strv, 0);
1162
13.6k
                    if (needs_coding(s)) {
1163
7.69k
                        char *d;
1164
7.69k
                        IGRAPH_CHECK(entity_encode(s, &d, IGRAPH_WRITE_GML_ENCODE_ONLY_QUOT_SW & options));
1165
7.69k
                        IGRAPH_FINALLY(igraph_free, d);
1166
7.69k
                        CHECK(fprintf(outstream, "    %s \"%s\"\n", newname, d));
1167
7.69k
                        IGRAPH_FREE(d);
1168
7.69k
                        IGRAPH_FINALLY_CLEAN(1);
1169
7.69k
                    } else {
1170
5.98k
                        CHECK(fprintf(outstream, "    %s \"%s\"\n", newname, s));
1171
5.98k
                    }
1172
13.6k
                } else if (type == IGRAPH_ATTRIBUTE_BOOLEAN) {
1173
7.42k
                    IGRAPH_CHECK(igraph_i_attribute_get_bool_vertex_attr(graph, name,
1174
7.42k
                                 igraph_vss_1(i), &boolv));
1175
7.42k
                    CHECK(fprintf(outstream, "    %s %d\n", newname, VECTOR(boolv)[0] ? 1 : 0));
1176
7.42k
                    WARN_ONCE(j, 1,
1177
7.42k
                              IGRAPH_WARNINGF("The boolean vertex attribute '%s' was converted to numeric.", name));
1178
7.42k
                } else {
1179
0
                    WARN_ONCE(j, 2,
1180
0
                              IGRAPH_WARNINGF("The non-numeric, non-string, non-boolean vertex attribute '%s' was ignored.", name));
1181
0
                }
1182
24.7k
            }
1183
25.1k
            IGRAPH_FREE(newname);
1184
25.1k
            IGRAPH_FINALLY_CLEAN(1);
1185
25.1k
        }
1186
34.7k
        CHECK(fprintf(outstream, "  ]\n"));
1187
34.7k
    }
1188
1189
    /* The edges too */
1190
3.33k
    IGRAPH_CHECK(igraph_vector_int_resize(&warning_shown, eattr_no));
1191
3.33k
    igraph_vector_int_null(&warning_shown);
1192
351k
    for (i = 0; i < no_of_edges; i++) {
1193
348k
        igraph_int_t from = IGRAPH_FROM(graph, i);
1194
348k
        igraph_int_t to = IGRAPH_TO(graph, i);
1195
348k
        igraph_int_t j;
1196
348k
        CHECK(fprintf(outstream, "  edge\n  [\n"));
1197
        /* source and target */
1198
348k
        CHECK(fprintf(outstream, "    source %" IGRAPH_PRId "\n",
1199
348k
                      myid ? (igraph_int_t)VECTOR(*myid)[from] : from));
1200
348k
        CHECK(fprintf(outstream, "    target %" IGRAPH_PRId "\n",
1201
348k
                      myid ? (igraph_int_t)VECTOR(*myid)[to] : to));
1202
1203
        /* other attributes */
1204
673k
        for (j = 0; j < eattr_no; j++) {
1205
324k
            igraph_attribute_type_t type = (igraph_attribute_type_t) VECTOR(etypes)[j];
1206
324k
            const char *name;
1207
324k
            char *newname;
1208
324k
            name = igraph_strvector_get(&enames, j);
1209
324k
            IGRAPH_CHECK(igraph_i_gml_convert_to_key(name, &newname));
1210
324k
            IGRAPH_FINALLY(igraph_free, newname);
1211
324k
            if (!strcmp(newname, "source") || !strcmp(newname, "target")) {
1212
751
                WARN_ONCE(j, 0,
1213
751
                          IGRAPH_WARNINGF("The edge attribute '%s' was ignored while writing GML format.", name));
1214
324k
            } else {
1215
324k
                if (type == IGRAPH_ATTRIBUTE_NUMERIC) {
1216
44.0k
                    IGRAPH_CHECK(igraph_i_attribute_get_numeric_edge_attr(graph, name,
1217
44.0k
                                 igraph_ess_1(i), &numv));
1218
                    /* Treat NaN as missing, skip writing it. GML does not officially support NaN. */
1219
44.0k
                    if (! isnan(VECTOR(numv)[0])) {
1220
1.83k
                        if (! isfinite(VECTOR(numv)[0])) {
1221
0
                            WARN_ONCE(j, 3,
1222
0
                                      IGRAPH_WARNINGF("Infinite value in numeric edge attribute '%s'. "
1223
0
                                                      "Produced GML file will not be conformant.", name));
1224
0
                        }
1225
1.83k
                        CHECK(fprintf(outstream, "    %s ", newname));
1226
1.83k
                        CHECK(igraph_real_fprintf_precise(outstream, VECTOR(numv)[0]));
1227
1.83k
                        CHECK(fputc('\n', outstream));
1228
1.83k
                    }
1229
280k
                } else if (type == IGRAPH_ATTRIBUTE_STRING) {
1230
238k
                    const char *s;
1231
238k
                    IGRAPH_CHECK(igraph_i_attribute_get_string_edge_attr(graph, name,
1232
238k
                                 igraph_ess_1(i), &strv));
1233
238k
                    s = igraph_strvector_get(&strv, 0);
1234
238k
                    if (needs_coding(s)) {
1235
1.92k
                        char *d;
1236
1.92k
                        IGRAPH_CHECK(entity_encode(s, &d, IGRAPH_WRITE_GML_ENCODE_ONLY_QUOT_SW & options));
1237
1.92k
                        IGRAPH_FINALLY(igraph_free, d);
1238
1.92k
                        CHECK(fprintf(outstream, "    %s \"%s\"\n", newname, d));
1239
1.92k
                        IGRAPH_FREE(d);
1240
1.92k
                        IGRAPH_FINALLY_CLEAN(1);
1241
236k
                    } else {
1242
236k
                        CHECK(fprintf(outstream, "    %s \"%s\"\n", newname, s));
1243
236k
                    }
1244
238k
                } else if (type == IGRAPH_ATTRIBUTE_BOOLEAN) {
1245
42.2k
                    IGRAPH_CHECK(igraph_i_attribute_get_bool_edge_attr(graph, name,
1246
42.2k
                                 igraph_ess_1(i), &boolv));
1247
42.2k
                    CHECK(fprintf(outstream, "    %s %d\n", newname, VECTOR(boolv)[0] ? 1 : 0));
1248
42.2k
                    WARN_ONCE(j, 1,
1249
42.2k
                              IGRAPH_WARNINGF("The boolean edge attribute '%s' was converted to numeric.", name));
1250
42.2k
                } else {
1251
0
                    WARN_ONCE(j, 2,
1252
0
                              IGRAPH_WARNINGF("The non-numeric, non-string, non-boolean edge attribute '%s' was ignored.", name));
1253
0
                }
1254
324k
            }
1255
324k
            IGRAPH_FREE(newname);
1256
324k
            IGRAPH_FINALLY_CLEAN(1);
1257
324k
        }
1258
348k
        CHECK(fprintf(outstream, "  ]\n"));
1259
348k
    }
1260
1261
3.33k
    CHECK(fprintf(outstream, "]\n"));
1262
1263
3.33k
#undef GETBIT
1264
3.33k
#undef SETBIT
1265
3.33k
#undef WARN_ONCE
1266
1267
3.33k
    if (&v_myid == myid) {
1268
14
        igraph_vector_destroy(&v_myid);
1269
14
        IGRAPH_FINALLY_CLEAN(1);
1270
14
    }
1271
1272
3.33k
    igraph_vector_int_destroy(&warning_shown);
1273
3.33k
    igraph_vector_bool_destroy(&boolv);
1274
3.33k
    igraph_strvector_destroy(&strv);
1275
3.33k
    igraph_vector_destroy(&numv);
1276
3.33k
    igraph_vector_int_destroy(&etypes);
1277
3.33k
    igraph_vector_int_destroy(&vtypes);
1278
3.33k
    igraph_vector_int_destroy(&gtypes);
1279
3.33k
    igraph_strvector_destroy(&enames);
1280
3.33k
    igraph_strvector_destroy(&vnames);
1281
3.33k
    igraph_strvector_destroy(&gnames);
1282
3.33k
    IGRAPH_FINALLY_CLEAN(10);
1283
1284
3.33k
    return IGRAPH_SUCCESS;
1285
3.33k
}
1286
1287
#undef CHECK