Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
280ed8dfbc4333e981d4e40f80a536d0cfdbe81f
[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   node = xbt_dynar_getfirst_as(g->nodes,xbt_node_t);
408   node->xbtdata = (void*) 1;
409   edge_list = node->out;
410   xbt_dynar_foreach(edge_list, cursor, e)
411     xbt_heap_push(heap,e, -(e->length));
412   
413   while((edge=xbt_heap_pop(heap))) {
414     if((edge->src->xbtdata) && (edge->dst->xbtdata)) continue;
415     tree[tree_size++]=edge;
416     if(!(edge->src->xbtdata)) {
417       edge->src->xbtdata = (void*) 1;
418       edge_list = edge->src->out;
419       xbt_dynar_foreach(edge_list, cursor, e) {
420         xbt_heap_push(heap,e, -(e->length));
421       }
422     } else {
423       edge->dst->xbtdata = (void*) 1;
424       edge_list = edge->dst->out;
425       xbt_dynar_foreach(edge_list, cursor, e) {
426         xbt_heap_push(heap,e, -(e->length));
427       }
428     }
429     if(tree_size==tree_size_max) break;
430   }
431   
432   xbt_heap_free(heap);
433
434   xbt_dynar_foreach(g->nodes, cursor, node) {
435     node->xbtdata = NULL;
436   }
437   return tree;
438 }
439
440 /********************* Import and Export ******************/
441 static xbt_graph_t parsed_graph = NULL;
442 static xbt_dict_t parsed_nodes = NULL;
443
444 static void *(*__parse_node_label_and_data)(xbt_node_t, const char*, const char*) = NULL;
445 static void *(*__parse_edge_label_and_data)(xbt_edge_t, const char*, const char*) = NULL;
446
447 static void __parse_graph_begin(void)
448 {
449
450   DEBUG0("<graph>");
451   if(A_graphxml_graph_isDirected == A_graphxml_graph_isDirected_true)
452     parsed_graph = xbt_graph_new_graph(1, NULL);
453   else parsed_graph = xbt_graph_new_graph(0, NULL);
454
455   parsed_nodes = xbt_dict_new();
456 }
457 static void __parse_graph_end(void)
458 {
459   xbt_dict_free(&parsed_nodes);
460   DEBUG0("</graph>");
461 }
462
463 static void __parse_node(void)
464 {
465   xbt_node_t node =
466       xbt_graph_new_node(parsed_graph, NULL);
467
468   DEBUG1("<node name=\"%s\"/>", A_graphxml_node_name);
469   if(__parse_node_label_and_data)
470     node->data = __parse_node_label_and_data(node,A_graphxml_node_label,
471                                              A_graphxml_node_data);
472   xbt_graph_parse_get_double(&(node->position_x),A_graphxml_node_position_x);
473   xbt_graph_parse_get_double(&(node->position_y),A_graphxml_node_position_y);
474
475   xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
476 }
477
478 static void __parse_edge(void)
479 {
480   xbt_edge_t edge =
481     xbt_graph_new_edge(parsed_graph,
482                        xbt_dict_get(parsed_nodes,A_graphxml_edge_source),
483                        xbt_dict_get(parsed_nodes,A_graphxml_edge_target),
484                        NULL);
485
486   if(__parse_edge_label_and_data)
487     edge->data = __parse_edge_label_and_data(edge,A_graphxml_edge_label,
488                                              A_graphxml_edge_data);
489
490   xbt_graph_parse_get_double(&(edge->length),A_graphxml_edge_length);
491
492   DEBUG3("<edge  source=\"%s\" target=\"%s\" length=\"%f\"/>",
493          (char *) (edge->src)->data,
494          (char *) (edge->dst)->data,
495          xbt_graph_edge_get_length(edge));
496 }
497
498 xbt_graph_t xbt_graph_read(const char *filename,
499                            void *(node_label_and_data)(xbt_node_t, const char*, const char*),
500                            void *(edge_label_and_data)(xbt_edge_t, const char*, const char*))
501 {
502
503   xbt_graph_t graph = NULL;
504
505   __parse_node_label_and_data = node_label_and_data;
506   __parse_edge_label_and_data = edge_label_and_data;
507
508   xbt_graph_parse_reset_parser();
509
510   STag_graphxml_graph_fun = __parse_graph_begin;
511   ETag_graphxml_graph_fun = __parse_graph_end;
512   ETag_graphxml_node_fun = __parse_node;
513   ETag_graphxml_edge_fun = __parse_edge;
514
515   xbt_graph_parse_open(filename);
516   xbt_assert1((!xbt_graph_parse()), "Parse error in %s", filename);
517   xbt_graph_parse_close();
518
519   graph = parsed_graph;
520   parsed_graph = NULL;
521
522   return graph;
523 }
524
525 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
526                                const char *(node_name) (xbt_node_t),
527                                const char *(edge_name) (xbt_edge_t))
528 {
529   int cursor = 0;
530   xbt_node_t node = NULL;
531   xbt_edge_t edge = NULL;
532   FILE *file = NULL;
533   const char *name=NULL;
534
535   file=fopen(filename,"w");
536   xbt_assert1(file, "Failed to open %s \n",filename);
537
538   if(g->directed) fprintf(file,"digraph test {\n");
539   else fprintf(file,"graph test {\n");
540
541   fprintf(file,"  graph [overlap=scale]\n");
542
543   fprintf(file,"  node [shape=box, style=filled]\n");
544   fprintf(file,"  node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
545   
546   xbt_dynar_foreach(g->nodes, cursor, node) {
547     fprintf(file,"  \"%p\" ", node);
548     if((node_name)&&((name=node_name(node)))) fprintf(file,"[label=\"%s\"]",name);
549     fprintf(file,";\n");
550   }
551   xbt_dynar_foreach(g->edges, cursor, edge) {
552     if(g->directed)
553       fprintf(file,"  \"%p\" -> \"%p\"",edge->src, edge->dst);
554     else
555       fprintf(file,"  \"%p\" -- \"%p\"",edge->src, edge->dst);
556     if((edge_name)&&((name=edge_name(edge)))) fprintf(file,"[label=\"%s\"]",name);
557     fprintf(file,";\n");
558   }
559   fprintf(file,"}\n");
560   fclose(file);
561 }
562
563 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
564                                const char *(node_name)(xbt_node_t),
565                                const char *(edge_name)(xbt_edge_t),
566                                const char *(node_data_print)(void *),
567                                const char *(edge_data_print)(void *))
568 {
569   int cursor = 0;
570   xbt_node_t node = NULL;
571   xbt_edge_t edge = NULL;
572   FILE *file = NULL;
573   const char *name = NULL;
574
575   file=fopen(filename,"w");
576   xbt_assert1(file, "Failed to open %s \n",filename);
577
578   fprintf(file,"<?xml version='1.0'?>\n");
579   fprintf(file,"<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
580   if(g->directed) fprintf(file,"<graph isDirected=\"true\">\n");
581   else fprintf(file,"<graph isDirected=\"false\">\n");
582   xbt_dynar_foreach(g->nodes, cursor, node) {
583     fprintf(file,"  <node name=\"%p\" ", node);
584     if((node_name)&&((name=node_name(node)))) fprintf(file,"label=\"%s\" ",name);
585     if((node_data_print)&&((name=node_data_print(node->data)))) 
586       fprintf(file,"data=\"%s\" ",name);
587     fprintf(file,">\n");
588   }
589   xbt_dynar_foreach(g->edges, cursor, edge) {
590     fprintf(file,"  <edge source=\"%p\" target =\"%p\" ",
591             edge->src, edge->dst );
592     if((edge_name)&&((name=edge_name(edge)))) fprintf(file,"label=\"%s\" ",name);
593     if(edge->length>=0.0) fprintf(file,"length=\"%g\" ",edge->length);
594     if((edge_data_print)&&((name=edge_data_print(edge->data)))) 
595       fprintf(file,"data=\"%s\" ",name);
596     fprintf(file,">\n");
597   }
598   fprintf(file,"</graph>\n");
599   fclose(file);
600 }
601
602 xbt_node_t* xbt_graph_topo_sort(xbt_graph_t g)
603 {
604  
605   xbt_node_t* sorted;
606   int cursor,idx;
607   xbt_node_t node;
608  unsigned long n;
609
610  n= xbt_dynar_length(g->nodes); 
611  idx=n-1;
612
613   sorted=xbt_malloc(n*sizeof(xbt_node_t));
614   xbt_dynar_foreach(g->nodes,cursor , node)
615     {
616       node->xbtdata=xbt_new0(int,1);
617     }
618
619   xbt_dynar_foreach(g->nodes,cursor , node) 
620     { 
621       xbt_graph_depth_visit(g,node,sorted,&idx);   
622     }
623           
624   return sorted; 
625 }
626
627 void xbt_graph_depth_visit(xbt_graph_t g,xbt_node_t n,xbt_node_t* sorted,int* idx )
628 {
629   int cursor;
630   xbt_edge_t edge;
631  
632   if (*((int*)(n->xbtdata))==ALREADY_EXPLORED)
633     return;
634   else if (*((int*)(n->xbtdata))==CURRENTLY_EXPLORING)
635     THROW0(0,0,"There is a cycle");
636   else
637     {
638       *((int*)(n->xbtdata))=CURRENTLY_EXPLORING;
639
640       xbt_dynar_foreach(n->out,cursor, edge)
641         {
642           xbt_graph_depth_visit(g,edge->dst,sorted,idx);
643         }
644  
645       *((int*)(n->xbtdata))=ALREADY_EXPLORED;
646       sorted[(*idx)--]=n;
647     }        
648 }