Logo AND Algorithmique Numérique Distribuée

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