Logo AND Algorithmique Numérique Distribuée

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