Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
A few more tiers file and a convenient perl script for the alnem project. I
[simgrid.git] / src / xbt / graph.c
1 /*      $Id$     */
2
3 /* a generic graph library.                                                 */
4
5 /* Copyright (c) 2006 Darina Dimitrova, Arnaud Legrand.                     */
6 /* All rights reserved.                                                     */
7
8 /* This program is free software; you can redistribute it and/or modify it
9  * under the terms of the license (GNU LGPL) which comes with this package. */
10
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
20
21
22
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(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   node->in = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
49   node->out = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
50   node->position_x = -1.0;
51   node->position_y = -1.0;
52
53   xbt_dynar_push(g->nodes, &node);
54
55   return node;
56 }
57
58 /** @brief add an edge to the given graph */
59 xbt_edge_t xbt_graph_new_edge(xbt_graph_t g,
60                               xbt_node_t src, xbt_node_t dst, void *data)
61 {
62   xbt_edge_t edge = NULL;
63
64
65   edge = xbt_new0(struct xbt_edge, 1);
66   xbt_dynar_push(src->out, &edge);
67   if (g->directed)
68     xbt_dynar_push(dst->in, &edge);
69   else                          /* only the "out" field is used */
70     xbt_dynar_push(dst->out, &edge);
71
72   edge->data = data;
73   edge->src = src;
74   edge->dst = dst;
75   if (!g->directed) {
76     xbt_dynar_push(src->in, &edge);
77     xbt_dynar_push(dst->out, &edge);
78   }
79
80
81   xbt_dynar_push(g->edges, &edge);
82
83   return edge;
84 }
85
86 void *xbt_graph_node_get_data(xbt_node_t node)
87 {
88   return node->data;
89 }
90
91 void xbt_graph_node_set_data(xbt_node_t node, void *data)
92 {
93   node->data = data;
94 }
95
96
97 void *xbt_graph_edge_get_data(xbt_edge_t edge)
98 {
99   return edge->data;
100 }
101
102 /** @brief Destructor
103  *  @param l: poor victim
104  *
105  * Free the graph structure. 
106  */
107 void xbt_graph_free_graph(xbt_graph_t g,
108                           void node_free_function(void *ptr),
109                           void edge_free_function(void *ptr),
110                           void graph_free_function(void *ptr))
111 {
112   int cursor = 0;
113   xbt_node_t node = NULL;
114   xbt_edge_t edge = NULL;
115
116
117   xbt_dynar_foreach(g->nodes, cursor, node) {
118     xbt_dynar_free(&(node->out));
119     xbt_dynar_free(&(node->in));
120     if (node_free_function)
121       node_free_function(node->data);
122   }
123
124   xbt_dynar_foreach(g->edges, cursor, edge) {
125     if (edge_free_function)
126       edge_free_function(edge->data);
127   }
128
129   xbt_dynar_foreach(g->nodes, cursor, node)
130       free(node);
131   xbt_dynar_free(&(g->nodes));
132
133   xbt_dynar_foreach(g->edges, cursor, edge)
134       free(edge);
135   xbt_dynar_free(&(g->edges));
136
137   free(g);
138
139   return;
140 }
141
142
143 /** @brief remove the given node from the given graph */
144 void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n,
145                          void_f_pvoid_t * node_free_function,
146                          void_f_pvoid_t * edge_free_function)
147 {
148   unsigned long nbr;
149   int i;
150   int cursor = 0;
151   xbt_node_t node = NULL;
152   xbt_edge_t edge = NULL;
153
154   nbr = xbt_dynar_length(g->edges);
155   cursor = 0;
156   for (i = 0; i < nbr; i++) {
157     xbt_dynar_cursor_get(g->edges, &cursor, &edge);
158
159     if ((edge->dst == n) || (edge->src == n)) {
160       xbt_graph_free_edge(g, edge, edge_free_function);
161     } else
162       xbt_dynar_cursor_step(g->edges, &cursor);
163   }
164
165   if ((node_free_function) && (n->data))
166     node_free_function(n->data);
167
168   cursor = 0;
169   xbt_dynar_foreach(g->nodes, cursor, node)
170     if (node == n)
171       xbt_dynar_cursor_rm(g->nodes, &cursor);
172
173   xbt_dynar_free(&(n->in));
174   xbt_dynar_free(&(n->out));
175
176   free(n);
177
178   return;
179 }
180
181 /** @brief remove the given edge from the given graph */
182 void xbt_graph_free_edge(xbt_graph_t g, xbt_edge_t e,
183                          void free_function(void *ptr))
184 {
185   int idx;
186   int cursor = 0;
187   xbt_edge_t edge = NULL;
188
189   if ((free_function) && (e->data))
190     free_function(e->data);
191
192   xbt_dynar_foreach(g->edges, cursor, edge) {
193     if (edge == e) {
194       if (g->directed) {
195         idx = __xbt_find_in_dynar(edge->dst->in, edge);
196         xbt_dynar_remove_at(edge->dst->in, idx, NULL);
197       } else {                  /* only the out field is used */
198         idx = __xbt_find_in_dynar(edge->dst->out, edge);
199         xbt_dynar_remove_at(edge->dst->out, idx, NULL);
200       }
201
202       idx = __xbt_find_in_dynar(edge->src->out, edge);
203       xbt_dynar_remove_at(edge->src->out, idx, NULL);
204
205       xbt_dynar_cursor_rm(g->edges, &cursor);
206       free(edge);
207       break;
208     }
209   }
210 }
211
212 int __xbt_find_in_dynar(xbt_dynar_t dynar, void *p)
213 {
214
215   int cursor = 0;
216   void *tmp = NULL;
217
218   xbt_dynar_foreach(dynar, cursor, tmp) {
219     if (tmp == p)
220       return cursor;
221   }
222   return -1;
223 }
224
225 /** @brief Retrieve the graph's nodes as a dynar */
226 xbt_dynar_t xbt_graph_get_nodes(xbt_graph_t g)
227 {
228   return g->nodes;
229 }
230
231 /** @brief Retrieve the graph's edges as a dynar */
232 xbt_dynar_t xbt_graph_get_edges(xbt_graph_t g)
233 {
234   return g->edges;
235 }
236
237 /** @brief Retrieve the node at the source of the given edge */
238 xbt_node_t xbt_graph_edge_get_source(xbt_edge_t e)
239 {
240
241   return e->src;
242 }
243
244 /** @brief Retrieve the node being the target of the given edge */
245 xbt_node_t xbt_graph_edge_get_target(xbt_edge_t e)
246 {
247   return e->dst;
248 }
249
250
251 /** @brief Set the weight of the given edge */
252 void xbt_graph_edge_set_length(xbt_edge_t e, double length)
253 {
254   e->length = length;
255
256 }
257
258 double xbt_graph_edge_get_length(xbt_edge_t e)
259 {
260   return e->length;
261 }
262
263
264 /** @brief construct the adjacency matrix corresponding to the given graph
265  * 
266  * The weights are the distances between nodes
267  */
268 double *xbt_graph_get_length_matrix(xbt_graph_t g)
269 {
270   int cursor = 0;
271   int in_cursor = 0;
272   int idx, i;
273   unsigned long n;
274   xbt_edge_t edge = NULL;
275   xbt_node_t node = NULL;
276   double *d = NULL;
277
278 # define D(u,v) d[(u)*n+(v)]
279   n = xbt_dynar_length(g->nodes);
280
281   d = (double *) xbt_new0(double, n * n);
282
283   for (i = 0; i < n * n; i++) {
284     d[i] = -1.0;
285   }
286
287   xbt_dynar_foreach(g->nodes, cursor, node) {
288     in_cursor = 0;
289     D(cursor, cursor) = 0;
290
291     xbt_dynar_foreach(node->out, in_cursor, edge) {
292       if (edge->dst == node)
293         idx = __xbt_find_in_dynar(g->nodes, edge->src);
294       else                      /*case of  undirected graphs */
295         idx = __xbt_find_in_dynar(g->nodes, edge->dst);
296       D(cursor, idx) = edge->length;
297     }
298   }
299
300 # undef D
301
302   return d;
303 }
304
305 /** @brief Floyd-Warshall algorithm for shortest path finding
306  * 
307  * From wikipedia: 
308  * 
309  * The Floyd–Warshall algorithm takes as input an adjacency matrix
310  * representation of a weighted, directed graph (V, E). The weight of a
311  * path between two vertices is the sum of the weights of the edges along
312  * that path. The edges E of the graph may have negative weights, but the
313  * graph must not have any negative weight cycles. The algorithm computes,
314  * for each pair of vertices, the minimum weight among all paths between
315  * the two vertices. The running time complexity is Θ(|V|3).
316  */
317 void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d,
318                          xbt_node_t * p)
319 {
320   int i, j, k;
321   unsigned long n;
322   n = xbt_dynar_length(g->nodes);
323
324 # define D(u,v) d[(u)*n+(v)]
325 # define P(u,v) p[(u)*n+(v)]
326
327   for (i = 0; i < n * n; i++) {
328     d[i] = adj[i];
329   }
330
331
332   for (i = 0; i < n; i++) {
333     for (j = 0; j < n; j++) {
334       if (D(i, j) != -1) {
335         P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i));
336       }
337     }
338   }
339
340   for (k = 0; k < n; k++) {
341     for (i = 0; i < n; i++) {
342       for (j = 0; j < n; j++) {
343         if ((D(i, k) != -1) && (D(k, j) != -1)) {
344           if ((D(i, j) == -1) || (D(i, j) > D(i, k) + D(k, j))) {
345             D(i, j) = D(i, k) + D(k, j);
346             P(i, j) = P(k, j);
347           }
348         }
349       }
350     }
351   }
352
353
354
355 # undef P
356 # undef D
357 }
358
359 /** @brief computes all-pairs shortest paths */
360 xbt_node_t *xbt_graph_shortest_paths(xbt_graph_t g)
361 {
362   xbt_node_t *p;
363   xbt_node_t *r;
364   int i, j, k;
365   unsigned long n;
366
367   double *adj = NULL;
368   double *d = NULL;
369
370 # define P(u,v) p[(u)*n+(v)]
371 # define R(u,v) r[(u)*n+(v)]
372
373   n = xbt_dynar_length(g->nodes);
374   adj = xbt_graph_get_length_matrix(g);
375   d = xbt_new0(double, n * n);
376   p = xbt_new0(xbt_node_t, n * n);
377   r = xbt_new0(xbt_node_t, n * n);
378
379   xbt_floyd_algorithm(g, adj, d, p);
380
381   for (i = 0; i < n; i++) {
382     for (j = 0; j < n; j++) {
383       k = j;
384
385       while ((P(i, k)) && (__xbt_find_in_dynar(g->nodes, P(i, k)) != i)) {
386         k = __xbt_find_in_dynar(g->nodes, P(i, k));
387       }
388
389       if (P(i, j)) {
390         R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k));
391       }
392     }
393   }
394 # undef R
395 # undef P
396
397   free(d);
398   free(p);
399   free(adj);
400   return r;
401 }
402
403 /** @brief Extract a spanning tree of the given graph */
404 xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g)
405 {
406   int tree_size = 0;
407   int tree_size_max = xbt_dynar_length(g->nodes) - 1;
408   xbt_edge_t *tree = xbt_new0(xbt_edge_t, tree_size_max);
409   xbt_edge_t e, edge;
410   xbt_node_t node = NULL;
411   xbt_dynar_t edge_list = NULL;
412   xbt_heap_t heap = xbt_heap_new(10, NULL);
413   int cursor;
414
415   xbt_assert0(!(g->directed),
416               "Spanning trees do not make sense on directed graphs");
417
418   xbt_dynar_foreach(g->nodes, cursor, node) {
419     node->xbtdata = NULL;
420   }
421
422   node = xbt_dynar_getfirst_as(g->nodes, xbt_node_t);
423   node->xbtdata = (void *) 1;
424   edge_list = node->out;
425   xbt_dynar_foreach(edge_list, cursor, e)
426       xbt_heap_push(heap, e, -(e->length));
427
428   while ((edge = xbt_heap_pop(heap))) {
429     if ((edge->src->xbtdata) && (edge->dst->xbtdata))
430       continue;
431     tree[tree_size++] = edge;
432     if (!(edge->src->xbtdata)) {
433       edge->src->xbtdata = (void *) 1;
434       edge_list = edge->src->out;
435       xbt_dynar_foreach(edge_list, cursor, e) {
436         xbt_heap_push(heap, e, -(e->length));
437       }
438     } else {
439       edge->dst->xbtdata = (void *) 1;
440       edge_list = edge->dst->out;
441       xbt_dynar_foreach(edge_list, cursor, e) {
442         xbt_heap_push(heap, e, -(e->length));
443       }
444     }
445     if (tree_size == tree_size_max)
446       break;
447   }
448
449   xbt_heap_free(heap);
450
451   return tree;
452 }
453
454 /** @brief Topological sort on the given graph 
455  *
456  *  From wikipedia:
457  * 
458  * In graph theory, a topological sort of a directed acyclic graph (DAG) is
459  * a linear ordering of its nodes which is compatible with the partial
460  * order R induced on the nodes where x comes before y (xRy) if there's a
461  * directed path from x to y in the DAG. An equivalent definition is that
462  * each node comes before all nodes to which it has edges. Every DAG has at
463  * least one topological sort, and may have many.
464  */
465 xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g)
466 {
467
468   xbt_node_t *sorted;
469   int cursor, idx;
470   xbt_node_t node;
471   unsigned long n;
472
473   n = xbt_dynar_length(g->nodes);
474   idx = n - 1;
475
476   sorted = xbt_malloc(n * sizeof(xbt_node_t));
477
478   xbt_dynar_foreach(g->nodes, cursor, node)
479     node->xbtdata = xbt_new0(int, 1);
480
481   xbt_dynar_foreach(g->nodes, cursor, node)
482     xbt_graph_depth_visit(g, node, sorted, &idx);
483
484   xbt_dynar_foreach(g->nodes, cursor, node) {
485     free(node->xbtdata);
486     node->xbtdata = NULL;
487   }
488
489   return sorted;
490 }
491
492 /** @brief First-depth graph traversal */
493 void xbt_graph_depth_visit(xbt_graph_t g, xbt_node_t n,
494                            xbt_node_t * sorted, int *idx)
495 {
496   int cursor;
497   xbt_edge_t edge;
498
499   if (*((int *) (n->xbtdata)) == ALREADY_EXPLORED)
500     return;
501   else if (*((int *) (n->xbtdata)) == CURRENTLY_EXPLORING)
502     THROW0(0, 0, "There is a cycle");
503   else {
504     *((int *) (n->xbtdata)) = CURRENTLY_EXPLORING;
505
506     xbt_dynar_foreach(n->out, cursor, edge) {
507       xbt_graph_depth_visit(g, edge->dst, sorted, idx);
508     }
509
510     *((int *) (n->xbtdata)) = ALREADY_EXPLORED;
511     sorted[(*idx)--] = n;
512   }
513 }
514
515 /********************* Import and Export ******************/
516 static xbt_graph_t parsed_graph = NULL;
517 static xbt_dict_t parsed_nodes = NULL;
518
519 static void *(*__parse_node_label_and_data) (xbt_node_t, const char *,
520                                              const char *) = NULL;
521 static void *(*__parse_edge_label_and_data) (xbt_edge_t, const char *,
522                                              const char *) = NULL;
523
524 static void __parse_graph_begin(void)
525 {
526   DEBUG0("<graph>");
527   if (A_graphxml_graph_isDirected == A_graphxml_graph_isDirected_true)
528     parsed_graph = xbt_graph_new_graph(1, NULL);
529   else
530     parsed_graph = xbt_graph_new_graph(0, NULL);
531
532   parsed_nodes = xbt_dict_new();
533 }
534
535 static void __parse_graph_end(void)
536 {
537   xbt_dict_free(&parsed_nodes);
538   DEBUG0("</graph>");
539 }
540
541 static void __parse_node(void)
542 {
543   xbt_node_t node = xbt_graph_new_node(parsed_graph, NULL);
544
545   DEBUG1("<node name=\"%s\"/>", A_graphxml_node_name);
546   if (__parse_node_label_and_data)
547     node->data = __parse_node_label_and_data(node, A_graphxml_node_label,
548                                              A_graphxml_node_data);
549   xbt_graph_parse_get_double(&(node->position_x),
550                              A_graphxml_node_position_x);
551   xbt_graph_parse_get_double(&(node->position_y),
552                              A_graphxml_node_position_y);
553
554   xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
555 }
556
557 static void __parse_edge(void)
558 {
559   xbt_edge_t edge = xbt_graph_new_edge(parsed_graph,
560                                        xbt_dict_get(parsed_nodes,
561                                                     A_graphxml_edge_source),
562                                        xbt_dict_get(parsed_nodes,
563                                                     A_graphxml_edge_target),
564                                        NULL);
565
566   if (__parse_edge_label_and_data)
567     edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label,
568                                              A_graphxml_edge_data);
569
570   xbt_graph_parse_get_double(&(edge->length), A_graphxml_edge_length);
571
572   DEBUG3("<edge  source=\"%s\" target=\"%s\" length=\"%f\"/>",
573          (char *) (edge->src)->data,
574          (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge));
575 }
576
577 /** @brief Import a graph from a file following the GraphXML format */
578 xbt_graph_t xbt_graph_read(const char *filename,
579                            void *(node_label_and_data) (xbt_node_t,
580                                                         const char *,
581                                                         const char *),
582                            void *(edge_label_and_data) (xbt_edge_t,
583                                                         const char *,
584                                                         const char *))
585 {
586
587   xbt_graph_t graph = NULL;
588
589   __parse_node_label_and_data = node_label_and_data;
590   __parse_edge_label_and_data = edge_label_and_data;
591
592   xbt_graph_parse_reset_parser();
593
594   STag_graphxml_graph_fun = __parse_graph_begin;
595   ETag_graphxml_graph_fun = __parse_graph_end;
596   ETag_graphxml_node_fun = __parse_node;
597   ETag_graphxml_edge_fun = __parse_edge;
598
599   xbt_graph_parse_open(filename);
600   xbt_assert1((!xbt_graph_parse()), "Parse error in %s", filename);
601   xbt_graph_parse_close();
602
603   graph = parsed_graph;
604   parsed_graph = NULL;
605
606   return graph;
607 }
608
609 /** @brief Export the given graph in the GraphViz formatting for visualization */
610 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
611                                const char *(node_name) (xbt_node_t),
612                                const char *(edge_name) (xbt_edge_t))
613 {
614   int cursor = 0;
615   xbt_node_t node = NULL;
616   xbt_edge_t edge = NULL;
617   FILE *file = NULL;
618   const char *name = NULL;
619
620   file = fopen(filename, "w");
621   xbt_assert1(file, "Failed to open %s \n", filename);
622
623   if (g->directed)
624     fprintf(file, "digraph test {\n");
625   else
626     fprintf(file, "graph test {\n");
627
628   fprintf(file, "  graph [overlap=scale]\n");
629
630   fprintf(file, "  node [shape=box, style=filled]\n");
631   fprintf(file,
632           "  node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
633
634   xbt_dynar_foreach(g->nodes, cursor, node) {
635     fprintf(file, "  \"%p\" ", node);
636     if ((node_name) && ((name = node_name(node))))
637       fprintf(file, "[label=\"%s\"]", name);
638     fprintf(file, ";\n");
639   }
640   xbt_dynar_foreach(g->edges, cursor, edge) {
641     if (g->directed)
642       fprintf(file, "  \"%p\" -> \"%p\"", edge->src, edge->dst);
643     else
644       fprintf(file, "  \"%p\" -- \"%p\"", edge->src, edge->dst);
645     if ((edge_name) && ((name = edge_name(edge))))
646       fprintf(file, "[label=\"%s\"]", name);
647     fprintf(file, ";\n");
648   }
649   fprintf(file, "}\n");
650   fclose(file);
651 }
652
653 /** @brief Export the given graph in the GraphXML format */
654 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
655                                const char *(node_name) (xbt_node_t),
656                                const char *(edge_name) (xbt_edge_t),
657                                const char *(node_data_print) (void *),
658                                const char *(edge_data_print) (void *))
659 {
660   int cursor = 0;
661   xbt_node_t node = NULL;
662   xbt_edge_t edge = NULL;
663   FILE *file = NULL;
664   const char *name = NULL;
665
666   file = fopen(filename, "w");
667   xbt_assert1(file, "Failed to open %s \n", filename);
668
669   fprintf(file, "<?xml version='1.0'?>\n");
670   fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
671   if (g->directed)
672     fprintf(file, "<graph isDirected=\"true\">\n");
673   else
674     fprintf(file, "<graph isDirected=\"false\">\n");
675   xbt_dynar_foreach(g->nodes, cursor, node) {
676     fprintf(file, "  <node name=\"%p\" ", node);
677     if ((node_name) && ((name = node_name(node))))
678       fprintf(file, "label=\"%s\" ", name);
679     if ((node_data_print) && ((name = node_data_print(node->data))))
680       fprintf(file, "data=\"%s\" ", name);
681     fprintf(file, ">\n");
682   }
683   xbt_dynar_foreach(g->edges, cursor, edge) {
684     fprintf(file, "  <edge source=\"%p\" target =\"%p\" ",
685             edge->src, edge->dst);
686     if ((edge_name) && ((name = edge_name(edge))))
687       fprintf(file, "label=\"%s\" ", name);
688     if (edge->length >= 0.0)
689       fprintf(file, "length=\"%g\" ", edge->length);
690     if ((edge_data_print) && ((name = edge_data_print(edge->data))))
691       fprintf(file, "data=\"%s\" ", name);
692     fprintf(file, ">\n");
693   }
694   fprintf(file, "</graph>\n");
695   fclose(file);
696 }