Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
document xbt graph functions
[simgrid.git] / src / xbt / graph.c
1 /* a generic graph library.                                                 */
2
3 /* Copyright (c) 2006, 2007, 2008, 2009, 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include "simgrid_config.h" /* getline */
10 #include <errno.h>
11 #include <stdlib.h>
12 #include "xbt/sysdep.h"
13 #include "xbt/log.h"
14 #include "xbt/graph.h"
15 #include "graph_private.h"
16 #include "xbt/graphxml_parse.h"
17 #include "xbt/dict.h"
18 #include "xbt/heap.h"
19 #include "xbt/str.h"
20
21
22
23
24 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_graph, xbt, "Graph");
25
26
27
28 /** @brief Constructor
29  *  @return a new graph
30  */
31 xbt_graph_t xbt_graph_new_graph(unsigned short int directed, void *data)
32 {
33   xbt_graph_t graph = NULL;
34   graph = xbt_new0(struct xbt_graph, 1);
35   graph->directed = directed;
36   graph->data = data;
37   graph->nodes = xbt_dynar_new(sizeof(xbt_node_t), NULL);
38   graph->edges = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
39
40   return graph;
41 }
42
43 /** @brief add a node to the given graph */
44 xbt_node_t xbt_graph_new_node(xbt_graph_t g, void *data)
45 {
46   xbt_node_t node = NULL;
47   node = xbt_new0(struct xbt_node, 1);
48   node->data = data;
49   if (g->directed)
50     /* only the "out" field is used */
51     node->in = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
52
53   node->out = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
54   node->position_x = -1.0;
55   node->position_y = -1.0;
56
57   xbt_dynar_push(g->nodes, &node);
58
59   return node;
60 }
61
62 /** @brief add an edge to the given graph */
63 xbt_edge_t xbt_graph_new_edge(xbt_graph_t g,
64                               xbt_node_t src, xbt_node_t dst, void *data)
65 {
66   xbt_edge_t edge = NULL;
67
68   edge = xbt_new0(struct xbt_edge, 1);
69   xbt_dynar_push(src->out, &edge);
70   if (g->directed)
71     xbt_dynar_push(dst->in, &edge);
72   else                          /* only the "out" field is used */
73     xbt_dynar_push(dst->out, &edge);
74
75   edge->data = data;
76   edge->src = src;
77   edge->dst = dst;
78
79   xbt_dynar_push(g->edges, &edge);
80
81   return edge;
82 }
83
84 /** @brief Get the edge connecting src and dst */
85 xbt_edge_t xbt_graph_get_edge(xbt_graph_t g, xbt_node_t src,
86                               xbt_node_t dst)
87 {
88   xbt_edge_t edge;
89   unsigned int cursor;
90
91   xbt_dynar_foreach(src->out, cursor, edge) {
92     XBT_DEBUG("%p = %p--%p", edge, edge->src, edge->dst);
93     if ((edge->src == src) && (edge->dst == dst))
94       return edge;
95   }
96   if (!g->directed) {
97     xbt_dynar_foreach(src->out, cursor, edge) {
98       XBT_DEBUG("%p = %p--%p", edge, edge->src, edge->dst);
99       if ((edge->dst == src) && (edge->src == dst))
100         return edge;
101     }
102   }
103   return NULL;
104 }
105
106 /** @brief Get the user data associated to a node */
107 void *xbt_graph_node_get_data(xbt_node_t node)
108 {
109   return node->data;
110 }
111
112 /** @brief Set the user data associated to a node */
113 void xbt_graph_node_set_data(xbt_node_t node, void *data)
114 {
115   node->data = data;
116 }
117
118 /** @brief Get the user data associated to a edge */
119 void *xbt_graph_edge_get_data(xbt_edge_t edge)
120 {
121   return edge->data;
122 }
123
124 /** @brief Set the user data associated to a edge */
125 void xbt_graph_edge_set_data(xbt_edge_t edge, void *data)
126 {
127   edge->data = data;
128 }
129
130 /** @brief Destructor
131  *  @param g: poor victim
132  *  @param node_free_function: function to use to free data associated to each node
133  *  @param edge_free_function: function to use to free data associated to each edge
134  *  @param graph_free_function: function to use to free data associated to g
135  *
136  * Free the graph structure.
137  */
138 void xbt_graph_free_graph(xbt_graph_t g,
139                           void_f_pvoid_t node_free_function,
140                           void_f_pvoid_t edge_free_function,
141                           void_f_pvoid_t graph_free_function)
142 {
143   unsigned int cursor = 0;
144   xbt_node_t node = NULL;
145   xbt_edge_t edge = NULL;
146
147
148   xbt_dynar_foreach(g->nodes, cursor, node) {
149     xbt_dynar_free(&(node->out));
150     xbt_dynar_free(&(node->in));
151     if (node_free_function)
152       node_free_function(node->data);
153   }
154
155   xbt_dynar_foreach(g->edges, cursor, edge) {
156     if (edge_free_function)
157       edge_free_function(edge->data);
158   }
159
160   xbt_dynar_foreach(g->nodes, cursor, node)
161       free(node);
162   xbt_dynar_free(&(g->nodes));
163
164   xbt_dynar_foreach(g->edges, cursor, edge)
165       free(edge);
166   xbt_dynar_free(&(g->edges));
167   if (graph_free_function)
168     graph_free_function(g->data);
169   free(g);
170   xbt_graph_parse_lex_destroy();
171   return;
172 }
173
174
175 /** @brief remove the given node from the given graph */
176 void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n,
177                          void_f_pvoid_t node_free_function,
178                          void_f_pvoid_t edge_free_function)
179 {
180   unsigned long nbr;
181   unsigned long i;
182   unsigned int cursor = 0;
183   xbt_node_t node = NULL;
184   xbt_edge_t edge = NULL;
185
186   nbr = xbt_dynar_length(g->edges);
187   cursor = 0;
188   for (i = 0; i < nbr; i++) {
189     xbt_dynar_get_cpy(g->edges, cursor, &edge);
190
191     if ((edge->dst == n) || (edge->src == n)) {
192       xbt_graph_free_edge(g, edge, edge_free_function);
193     } else
194       cursor++;
195   }
196
197   if ((node_free_function) && (n->data))
198     node_free_function(n->data);
199
200   cursor = 0;
201   xbt_dynar_foreach(g->nodes, cursor, node)
202       if (node == n)
203     xbt_dynar_cursor_rm(g->nodes, &cursor);
204
205   xbt_dynar_free(&(n->in));
206   xbt_dynar_free(&(n->out));
207
208   free(n);
209
210   return;
211 }
212
213 /** @brief remove the given edge from the given graph */
214 void xbt_graph_free_edge(xbt_graph_t g, xbt_edge_t e,
215                          void_f_pvoid_t free_function)
216 {
217   int idx;
218   unsigned int cursor = 0;
219   xbt_edge_t edge = NULL;
220
221   if ((free_function) && (e->data))
222     free_function(e->data);
223
224   xbt_dynar_foreach(g->edges, cursor, edge) {
225     if (edge == e) {
226       if (g->directed) {
227         idx = __xbt_find_in_dynar(edge->dst->in, edge);
228         xbt_dynar_remove_at(edge->dst->in, idx, NULL);
229       } else {                  /* only the out field is used */
230         idx = __xbt_find_in_dynar(edge->dst->out, edge);
231         xbt_dynar_remove_at(edge->dst->out, idx, NULL);
232       }
233
234       idx = __xbt_find_in_dynar(edge->src->out, edge);
235       xbt_dynar_remove_at(edge->src->out, idx, NULL);
236
237       xbt_dynar_cursor_rm(g->edges, &cursor);
238       free(edge);
239       break;
240     }
241   }
242 }
243
244 int __xbt_find_in_dynar(xbt_dynar_t dynar, void *p)
245 {
246
247   unsigned int cursor = 0;
248   void *tmp = NULL;
249
250   xbt_dynar_foreach(dynar, cursor, tmp) {
251     if (tmp == p)
252       return cursor;
253   }
254   return -1;
255 }
256
257 /** @brief Retrieve the graph's nodes as a dynar */
258 xbt_dynar_t xbt_graph_get_nodes(xbt_graph_t g)
259 {
260   return g->nodes;
261 }
262
263 /** @brief Retrieve the graph's edges as a dynar */
264 xbt_dynar_t xbt_graph_get_edges(xbt_graph_t g)
265 {
266   return g->edges;
267 }
268
269 /** @brief Retrieve the node at the source of the given edge */
270 xbt_node_t xbt_graph_edge_get_source(xbt_edge_t e)
271 {
272   return e->src;
273 }
274
275 /** @brief Retrieve the node being the target of the given edge */
276 xbt_node_t xbt_graph_edge_get_target(xbt_edge_t e)
277 {
278   return e->dst;
279 }
280
281 /** @brief Retrieve the outgoing edges of the given node */
282 xbt_dynar_t xbt_graph_node_get_outedges(xbt_node_t n)
283 {
284   return n->out;
285 }
286
287 /** @brief Set the weight of the given edge */
288 void xbt_graph_edge_set_length(xbt_edge_t e, double length)
289 {
290   e->length = length;
291
292 }
293
294 /** @brief Get the length of a edge */
295 double xbt_graph_edge_get_length(xbt_edge_t edge)
296 {
297   return edge->length;
298 }
299
300
301 /** @brief construct the adjacency matrix corresponding to the given graph
302  *
303  * The weights are the distances between nodes
304  */
305 double *xbt_graph_get_length_matrix(xbt_graph_t g)
306 {
307   unsigned int cursor = 0;
308   unsigned int in_cursor = 0;
309   unsigned long idx, i;
310   unsigned long n;
311   xbt_edge_t edge = NULL;
312   xbt_node_t node = NULL;
313   double *d = NULL;
314
315 # define D(u,v) d[(u)*n+(v)]
316   n = xbt_dynar_length(g->nodes);
317
318   d = (double *) xbt_new0(double, n * n);
319
320   for (i = 0; i < n * n; i++) {
321     d[i] = -1.0;
322   }
323
324   xbt_dynar_foreach(g->nodes, cursor, node) {
325     in_cursor = 0;
326     D(cursor, cursor) = 0;
327
328     xbt_dynar_foreach(node->out, in_cursor, edge) {
329       if (edge->dst == node)
330         idx = __xbt_find_in_dynar(g->nodes, edge->src);
331       else                      /*case of  undirected graphs */
332         idx = __xbt_find_in_dynar(g->nodes, edge->dst);
333       D(cursor, idx) = edge->length;
334     }
335   }
336
337 # undef D
338
339   return d;
340 }
341
342 /** @brief Floyd-Warshall algorithm for shortest path finding
343  *
344  * From wikipedia:
345  *
346  * The Floyd–Warshall algorithm takes as input an adjacency matrix
347  * representation of a weighted, directed graph (V, E). The weight of a
348  * path between two vertices is the sum of the weights of the edges along
349  * that path. The edges E of the graph may have negative weights, but the
350  * graph must not have any negative weight cycles. The algorithm computes,
351  * for each pair of vertices, the minimum weight among all paths between
352  * the two vertices. The running time complexity is Θ(|V|3).
353  */
354 void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d,
355                          xbt_node_t * p)
356 {
357   unsigned long i, j, k;
358   unsigned long n;
359   n = xbt_dynar_length(g->nodes);
360
361 # define D(u,v) d[(u)*n+(v)]
362 # define P(u,v) p[(u)*n+(v)]
363
364   for (i = 0; i < n * n; i++) {
365     d[i] = adj[i];
366   }
367
368
369   for (i = 0; i < n; i++) {
370     for (j = 0; j < n; j++) {
371       if (D(i, j) != -1) {
372         P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i));
373       }
374     }
375   }
376
377   for (k = 0; k < n; k++) {
378     for (i = 0; i < n; i++) {
379       for (j = 0; j < n; j++) {
380         if ((D(i, k) != -1) && (D(k, j) != -1)) {
381           if ((D(i, j) == -1) || (D(i, j) > D(i, k) + D(k, j))) {
382             D(i, j) = D(i, k) + D(k, j);
383             P(i, j) = P(k, j);
384           }
385         }
386       }
387     }
388   }
389
390
391
392 # undef P
393 # undef D
394 }
395
396 /** @brief computes all-pairs shortest paths */
397 xbt_node_t *xbt_graph_shortest_paths(xbt_graph_t g)
398 {
399   xbt_node_t *p;
400   xbt_node_t *r;
401   unsigned long i, j, k;
402   unsigned long n;
403
404   double *adj = NULL;
405   double *d = NULL;
406
407 # define P(u,v) p[(u)*n+(v)]
408 # define R(u,v) r[(u)*n+(v)]
409
410   n = xbt_dynar_length(g->nodes);
411   adj = xbt_graph_get_length_matrix(g);
412   d = xbt_new0(double, n * n);
413   p = xbt_new0(xbt_node_t, n * n);
414   r = xbt_new0(xbt_node_t, n * n);
415
416   xbt_floyd_algorithm(g, adj, d, p);
417
418   for (i = 0; i < n; i++) {
419     for (j = 0; j < n; j++) {
420       k = j;
421
422       while ((P(i, k)) && (__xbt_find_in_dynar(g->nodes, P(i, k)) != i)) {
423         k = __xbt_find_in_dynar(g->nodes, P(i, k));
424       }
425
426       if (P(i, j)) {
427         R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k));
428       }
429     }
430   }
431 # undef R
432 # undef P
433
434   free(d);
435   free(p);
436   free(adj);
437   return r;
438 }
439
440 /** @brief Extract a spanning tree of the given graph */
441 xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g)
442 {
443   int tree_size = 0;
444   int tree_size_max = xbt_dynar_length(g->nodes) - 1;
445   xbt_edge_t *tree = xbt_new0(xbt_edge_t, tree_size_max);
446   xbt_edge_t e, edge;
447   xbt_node_t node = NULL;
448   xbt_dynar_t edge_list = NULL;
449   xbt_heap_t heap = xbt_heap_new(10, NULL);
450   unsigned int cursor;
451
452   xbt_assert(!(g->directed),
453               "Spanning trees do not make sense on directed graphs");
454
455   xbt_dynar_foreach(g->nodes, cursor, node) {
456     node->xbtdata = NULL;
457   }
458
459   node = xbt_dynar_getfirst_as(g->nodes, xbt_node_t);
460   node->xbtdata = (void *) 1;
461   edge_list = node->out;
462   xbt_dynar_foreach(edge_list, cursor, e)
463       xbt_heap_push(heap, e, -(e->length));
464
465   while ((edge = xbt_heap_pop(heap))) {
466     if ((edge->src->xbtdata) && (edge->dst->xbtdata))
467       continue;
468     tree[tree_size++] = edge;
469     if (!(edge->src->xbtdata)) {
470       edge->src->xbtdata = (void *) 1;
471       edge_list = edge->src->out;
472       xbt_dynar_foreach(edge_list, cursor, e) {
473         xbt_heap_push(heap, e, -(e->length));
474       }
475     } else {
476       edge->dst->xbtdata = (void *) 1;
477       edge_list = edge->dst->out;
478       xbt_dynar_foreach(edge_list, cursor, e) {
479         xbt_heap_push(heap, e, -(e->length));
480       }
481     }
482     if (tree_size == tree_size_max)
483       break;
484   }
485
486   xbt_heap_free(heap);
487
488   return tree;
489 }
490
491 /** @brief Topological sort on the given graph
492  *
493  *  From wikipedia:
494  *
495  * In graph theory, a topological sort of a directed acyclic graph (DAG) is
496  * a linear ordering of its nodes which is compatible with the partial
497  * order R induced on the nodes where x comes before y (xRy) if there's a
498  * directed path from x to y in the DAG. An equivalent definition is that
499  * each node comes before all nodes to which it has edges. Every DAG has at
500  * least one topological sort, and may have many.
501  */
502 xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g)
503 {
504
505   xbt_node_t *sorted;
506   unsigned int cursor;
507   int idx;
508   xbt_node_t node;
509   unsigned long n;
510
511   n = xbt_dynar_length(g->nodes);
512   idx = n - 1;
513
514   sorted = xbt_malloc(n * sizeof(xbt_node_t));
515
516   xbt_dynar_foreach(g->nodes, cursor, node)
517       node->xbtdata = xbt_new0(int, 1);
518
519   xbt_dynar_foreach(g->nodes, cursor, node)
520       xbt_graph_depth_visit(g, node, sorted, &idx);
521
522   xbt_dynar_foreach(g->nodes, cursor, node) {
523     free(node->xbtdata);
524     node->xbtdata = NULL;
525   }
526
527   return sorted;
528 }
529
530 /** @brief First-depth graph traversal */
531 void xbt_graph_depth_visit(xbt_graph_t g, xbt_node_t n,
532                            xbt_node_t * sorted, int *idx)
533 {
534   unsigned int cursor;
535   xbt_edge_t edge;
536
537   if (*((int *) (n->xbtdata)) == ALREADY_EXPLORED)
538     return;
539   else if (*((int *) (n->xbtdata)) == CURRENTLY_EXPLORING)
540     THROWF(0, 0, "There is a cycle");
541   else {
542     *((int *) (n->xbtdata)) = CURRENTLY_EXPLORING;
543
544     xbt_dynar_foreach(n->out, cursor, edge) {
545       xbt_graph_depth_visit(g, edge->dst, sorted, idx);
546     }
547
548     *((int *) (n->xbtdata)) = ALREADY_EXPLORED;
549     sorted[(*idx)--] = n;
550   }
551 }
552
553 /********************* Import and Export ******************/
554 static xbt_graph_t parsed_graph = NULL;
555 static xbt_dict_t parsed_nodes = NULL;
556
557 static void *(*__parse_node_label_and_data) (xbt_node_t, const char *,
558                                              const char *) = NULL;
559 static void *(*__parse_edge_label_and_data) (xbt_edge_t, const char *,
560                                              const char *) = NULL;
561
562 static void __parse_graph_begin(void)
563 {
564   XBT_DEBUG("<graph>");
565   if (A_graphxml_graph_isDirected == A_graphxml_graph_isDirected_true)
566     parsed_graph = xbt_graph_new_graph(1, NULL);
567   else
568     parsed_graph = xbt_graph_new_graph(0, NULL);
569
570   parsed_nodes = xbt_dict_new_homogeneous(NULL);
571 }
572
573 static void __parse_graph_end(void)
574 {
575   xbt_dict_free(&parsed_nodes);
576   XBT_DEBUG("</graph>");
577 }
578
579 static void __parse_node(void)
580 {
581   xbt_node_t node = xbt_graph_new_node(parsed_graph, NULL);
582
583   XBT_DEBUG("<node name=\"%s\"/>", A_graphxml_node_name);
584   if (__parse_node_label_and_data)
585     node->data = __parse_node_label_and_data(node, A_graphxml_node_label,
586                                              A_graphxml_node_data);
587   node->position_x = xbt_graph_parse_get_double(A_graphxml_node_position_x);
588   node->position_y = xbt_graph_parse_get_double(A_graphxml_node_position_y);
589
590   xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
591 }
592
593 static void __parse_edge(void)
594 {
595   xbt_edge_t edge = xbt_graph_new_edge(parsed_graph,
596                                        xbt_dict_get(parsed_nodes,
597                                                     A_graphxml_edge_source),
598                                        xbt_dict_get(parsed_nodes,
599                                                     A_graphxml_edge_target),
600                                        NULL);
601
602   if (__parse_edge_label_and_data)
603     edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label,
604                                              A_graphxml_edge_data);
605
606   edge->length = xbt_graph_parse_get_double(A_graphxml_edge_length);
607
608   XBT_DEBUG("<edge  source=\"%s\" target=\"%s\" length=\"%f\"/>",
609          (char *) (edge->src)->data,
610          (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge));
611 }
612
613 /** @brief Import a graph from a file following the GraphXML format */
614 xbt_graph_t xbt_graph_read(const char *filename,
615                            void *(*node_label_and_data) (xbt_node_t,
616                                                          const char *,
617                                                          const char *),
618                            void *(*edge_label_and_data) (xbt_edge_t,
619                                                          const char *,
620                                                          const char *))
621 {
622
623   xbt_graph_t graph = NULL;
624
625   __parse_node_label_and_data = node_label_and_data;
626   __parse_edge_label_and_data = edge_label_and_data;
627
628   xbt_graph_parse_reset_parser();
629
630   STag_graphxml_graph_fun = __parse_graph_begin;
631   ETag_graphxml_graph_fun = __parse_graph_end;
632   ETag_graphxml_node_fun = __parse_node;
633   ETag_graphxml_edge_fun = __parse_edge;
634
635   xbt_graph_parse_open(filename);
636   _XBT_GNUC_UNUSED int res;
637   res = xbt_graph_parse();
638   xbt_assert(!res, "Parse error in %s", filename);
639   xbt_graph_parse_close();
640
641   graph = parsed_graph;
642   parsed_graph = NULL;
643
644   return graph;
645 }
646
647 /** @brief Export the given graph in the GraphViz formatting for visualization */
648 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
649                                const char *(node_name) (xbt_node_t),
650                                const char *(edge_name) (xbt_edge_t))
651 {
652   unsigned int cursor = 0;
653   xbt_node_t node = NULL;
654   xbt_edge_t edge = NULL;
655   FILE *file = NULL;
656   const char *name = NULL;
657
658   file = fopen(filename, "w");
659   xbt_assert(file, "Failed to open %s \n", filename);
660
661   if (g->directed)
662     fprintf(file, "digraph test {\n");
663   else
664     fprintf(file, "graph test {\n");
665
666   fprintf(file, "  graph [overlap=scale]\n");
667
668   fprintf(file, "  node [shape=box, style=filled]\n");
669   fprintf(file,
670           "  node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
671
672   xbt_dynar_foreach(g->nodes, cursor, node) {
673     fprintf(file, "  \"%p\" ", node);
674     if ((node_name) && ((name = node_name(node))))
675       fprintf(file, "[label=\"%s\"]", name);
676     fprintf(file, ";\n");
677   }
678   xbt_dynar_foreach(g->edges, cursor, edge) {
679     if (g->directed)
680       fprintf(file, "  \"%p\" -> \"%p\"", edge->src, edge->dst);
681     else
682       fprintf(file, "  \"%p\" -- \"%p\"", edge->src, edge->dst);
683     if ((edge_name) && ((name = edge_name(edge))))
684       fprintf(file, "[label=\"%s\"]", name);
685     fprintf(file, ";\n");
686   }
687   fprintf(file, "}\n");
688   fclose(file);
689 }
690
691 /** @brief Export the given graph in the GraphXML format */
692 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
693                                const char *(node_name) (xbt_node_t),
694                                const char *(edge_name) (xbt_edge_t),
695                                const char *(node_data_print) (void *),
696                                const char *(edge_data_print) (void *))
697 {
698   unsigned int cursor = 0;
699   xbt_node_t node = NULL;
700   xbt_edge_t edge = NULL;
701   FILE *file = NULL;
702   const char *name = NULL;
703
704   file = fopen(filename, "w");
705   xbt_assert(file, "Failed to open %s \n", filename);
706
707   fprintf(file, "<?xml version='1.0'?>\n");
708   fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
709   if (g->directed)
710     fprintf(file, "<graph isDirected=\"true\">\n");
711   else
712     fprintf(file, "<graph isDirected=\"false\">\n");
713   xbt_dynar_foreach(g->nodes, cursor, node) {
714     fprintf(file, "  <node name=\"%p\" ", node);
715     if ((node_name) && ((name = node_name(node))))
716       fprintf(file, "label=\"%s\" ", name);
717     if ((node_data_print) && ((name = node_data_print(node->data))))
718       fprintf(file, "data=\"%s\" ", name);
719     fprintf(file, ">\n");
720   }
721   xbt_dynar_foreach(g->edges, cursor, edge) {
722     fprintf(file, "  <edge source=\"%p\" target =\"%p\" ",
723             edge->src, edge->dst);
724     if ((edge_name) && ((name = edge_name(edge))))
725       fprintf(file, "label=\"%s\" ", name);
726     if (edge->length >= 0.0)
727       fprintf(file, "length=\"%g\" ", edge->length);
728     if ((edge_data_print) && ((name = edge_data_print(edge->data))))
729       fprintf(file, "data=\"%s\" ", name);
730     fprintf(file, ">\n");
731   }
732   fprintf(file, "</graph>\n");
733   fclose(file);
734 }
735
736 /** @brief Load a graph from a file (in the SimGrid Graph format) */
737 xbt_graph_t xbt_graph_load (const char *filename)
738 {
739   FILE *file = NULL;
740   ssize_t read;
741   file = fopen (filename, "r");
742   xbt_assert(file, "Failed to open %s \n", filename);
743
744   xbt_dict_t nodes_dict = xbt_dict_new_homogeneous(NULL);
745   xbt_graph_t ret = xbt_graph_new_graph (0, NULL);
746
747   //read the number of nodes
748   size_t size;
749   char *nnodes_str = NULL;
750   read = getline (&nnodes_str, &size, file);
751   if (read == -1)
752     THROWF(system_error, 0, "getline failed to read the number of nodes (errno = %d)", errno);
753   int i, nnodes = atoi (nnodes_str);
754   free (nnodes_str);
755
756   //read all nodes
757   for (i = 0; i < nnodes; i++){
758     char *node_str = NULL;
759     read = getline (&node_str, &size, file);
760     if (read == -1)
761       THROWF(system_error, 0, "getline failed to read all nodes (errno = %d)", errno);
762     xbt_node_t n;
763     char *name = xbt_strdup (node_str);
764     xbt_str_subst (name, '\n', '\0', 0);
765     n = xbt_graph_new_node (ret, name);
766     xbt_dict_set (nodes_dict, name, n, NULL);
767     free (node_str);
768   }
769
770   //read the number of edges
771   char *nedges_str = NULL;
772   read = getline (&nedges_str, &size, file);
773   if (read == -1)
774     THROWF(system_error, 0, "getline failed to read the number of edges (errno = %d)", errno);
775   int nedges = atoi (nedges_str);
776   free (nedges_str);
777
778   //read all edges
779   for (i = 0; i < nedges; i++){
780     char *edge_str = NULL, edge_id[200], node_source[200], node_target[200];
781     read = getline (&edge_str, &size, file);
782     if (read == -1)
783       THROWF(system_error, 0, "getline failed to read all edges (errno = %d)", errno);
784     sscanf (edge_str, "%s %s %s", edge_id, node_source, node_target);
785     free (edge_str);
786     xbt_str_subst (edge_id, '\n', '\0', 0);
787     xbt_str_subst (node_source, '\n', '\0', 0);
788     xbt_str_subst (node_target, '\n', '\0', 0);
789
790     xbt_node_t source = xbt_dict_get (nodes_dict, node_source);
791     xbt_node_t target = xbt_dict_get (nodes_dict, node_target);
792     xbt_graph_new_edge (ret, source, target, xbt_strdup(edge_id));
793   }
794   xbt_dict_free (&nodes_dict);
795   return ret;
796 }
797
798 /** @brief Save a graph from a file (in the SimGrid Graph format) */
799 void xbt_graph_save (xbt_graph_t span,
800                      const char *filename,
801                      const char *(nname) (xbt_node_t),
802                      const char *(ename) (xbt_edge_t))
803 {
804   FILE *file = NULL;
805   file = fopen(filename, "w");
806   xbt_assert(file, "Failed to open %s \n", filename);
807
808   xbt_dynar_t nodes = xbt_graph_get_nodes (span);
809   xbt_dynar_t edges = xbt_graph_get_edges (span);
810   unsigned int cpt;
811   xbt_node_t node;
812   fprintf (file, "%lu\n", xbt_dynar_length (nodes));
813   xbt_dynar_foreach (nodes, cpt, node) {
814     if (nname){
815       fprintf (file, "%s\n", nname(node));
816     }else{
817       fprintf (file, "%p\n", node);
818     }
819   }
820   fprintf (file, "%lu\n", xbt_dynar_length (edges));
821   xbt_edge_t edge;
822   xbt_dynar_foreach (edges, cpt, edge) {
823     xbt_node_t source = xbt_graph_edge_get_source (edge);
824     xbt_node_t target = xbt_graph_edge_get_target (edge);
825     if (ename){
826       if (nname){
827         fprintf (file, "%s %s %s\n", ename(edge), nname(source), nname(target));
828       }else{
829         fprintf (file, "%s %p %p\n", ename(edge), source, target);
830       }
831     }else{
832       if (nname){
833         fprintf (file, "%p %s %s\n", edge, nname(source), nname(target));
834       }else{
835         fprintf (file, "%p %p %p\n", edge, source, target);
836       }
837     }
838   }
839   fclose (file);
840 }