Logo AND Algorithmique Numérique Distribuée

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