1 /* a generic graph library. */
3 /* Copyright (c) 2006, 2007, 2008, 2009, 2010. The SimGrid Team.
4 * All rights reserved. */
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. */
9 #include "simgrid_config.h" /* getline */
11 #include "xbt/sysdep.h"
13 #include "xbt/graph.h"
14 #include "graph_private.h"
15 #include "xbt/graphxml_parse.h"
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_graph, xbt, "Graph");
27 /** @brief Constructor
30 xbt_graph_t xbt_graph_new_graph(unsigned short int directed, void *data)
32 xbt_graph_t graph = NULL;
33 graph = xbt_new0(struct xbt_graph, 1);
34 graph->directed = directed;
36 graph->nodes = xbt_dynar_new(sizeof(xbt_node_t), NULL);
37 graph->edges = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
42 /** @brief add a node to the given graph */
43 xbt_node_t xbt_graph_new_node(xbt_graph_t g, void *data)
45 xbt_node_t node = NULL;
46 node = xbt_new0(struct xbt_node, 1);
49 /* only the "out" field is used */
50 node->in = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
52 node->out = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
53 node->position_x = -1.0;
54 node->position_y = -1.0;
56 xbt_dynar_push(g->nodes, &node);
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)
65 xbt_edge_t edge = NULL;
67 edge = xbt_new0(struct xbt_edge, 1);
68 xbt_dynar_push(src->out, &edge);
70 xbt_dynar_push(dst->in, &edge);
71 else /* only the "out" field is used */
72 xbt_dynar_push(dst->out, &edge);
78 xbt_dynar_push(g->edges, &edge);
83 xbt_edge_t xbt_graph_get_edge(xbt_graph_t g, xbt_node_t src,
89 xbt_dynar_foreach(src->out, cursor, edge) {
90 XBT_DEBUG("%p = %p--%p", edge, edge->src, edge->dst);
91 if ((edge->src == src) && (edge->dst == dst))
95 xbt_dynar_foreach(src->out, cursor, edge) {
96 XBT_DEBUG("%p = %p--%p", edge, edge->src, edge->dst);
97 if ((edge->dst == src) && (edge->src == dst))
104 void *xbt_graph_node_get_data(xbt_node_t node)
109 void xbt_graph_node_set_data(xbt_node_t node, void *data)
114 void *xbt_graph_edge_get_data(xbt_edge_t edge)
119 void xbt_graph_edge_set_data(xbt_edge_t edge, void *data)
124 /** @brief Destructor
125 * @param g: poor victim
126 * @param node_free_function: function to use to free data associated to each node
127 * @param edge_free_function: function to use to free data associated to each edge
128 * @param graph_free_function: function to use to free data associated to g
130 * Free the graph structure.
132 void xbt_graph_free_graph(xbt_graph_t g,
133 void_f_pvoid_t node_free_function,
134 void_f_pvoid_t edge_free_function,
135 void_f_pvoid_t graph_free_function)
137 unsigned int cursor = 0;
138 xbt_node_t node = NULL;
139 xbt_edge_t edge = NULL;
142 xbt_dynar_foreach(g->nodes, cursor, node) {
143 xbt_dynar_free(&(node->out));
144 xbt_dynar_free(&(node->in));
145 if (node_free_function)
146 (*node_free_function) (node->data);
149 xbt_dynar_foreach(g->edges, cursor, edge) {
150 if (edge_free_function)
151 (*edge_free_function) (edge->data);
154 xbt_dynar_foreach(g->nodes, cursor, node)
156 xbt_dynar_free(&(g->nodes));
158 xbt_dynar_foreach(g->edges, cursor, edge)
160 xbt_dynar_free(&(g->edges));
161 if (graph_free_function)
162 (*graph_free_function) (g->data);
164 xbt_graph_parse_lex_destroy();
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)
176 unsigned int cursor = 0;
177 xbt_node_t node = NULL;
178 xbt_edge_t edge = NULL;
180 nbr = xbt_dynar_length(g->edges);
182 for (i = 0; i < nbr; i++) {
183 xbt_dynar_get_cpy(g->edges, cursor, &edge);
185 if ((edge->dst == n) || (edge->src == n)) {
186 xbt_graph_free_edge(g, edge, edge_free_function);
191 if ((node_free_function) && (n->data))
192 (*node_free_function) (n->data);
195 xbt_dynar_foreach(g->nodes, cursor, node)
197 xbt_dynar_cursor_rm(g->nodes, &cursor);
199 xbt_dynar_free(&(n->in));
200 xbt_dynar_free(&(n->out));
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)
212 unsigned int cursor = 0;
213 xbt_edge_t edge = NULL;
215 if ((free_function) && (e->data))
216 (*free_function) (e->data);
218 xbt_dynar_foreach(g->edges, cursor, edge) {
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);
228 idx = __xbt_find_in_dynar(edge->src->out, edge);
229 xbt_dynar_remove_at(edge->src->out, idx, NULL);
231 xbt_dynar_cursor_rm(g->edges, &cursor);
238 int __xbt_find_in_dynar(xbt_dynar_t dynar, void *p)
241 unsigned int cursor = 0;
244 xbt_dynar_foreach(dynar, cursor, tmp) {
251 /** @brief Retrieve the graph's nodes as a dynar */
252 xbt_dynar_t xbt_graph_get_nodes(xbt_graph_t g)
257 /** @brief Retrieve the graph's edges as a dynar */
258 xbt_dynar_t xbt_graph_get_edges(xbt_graph_t g)
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)
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)
275 /** @brief Retrieve the outgoing edges of the given node */
276 xbt_dynar_t xbt_graph_node_get_outedges(xbt_node_t n)
281 /** @brief Set the weight of the given edge */
282 void xbt_graph_edge_set_length(xbt_edge_t e, double length)
288 double xbt_graph_edge_get_length(xbt_edge_t e)
294 /** @brief construct the adjacency matrix corresponding to the given graph
296 * The weights are the distances between nodes
298 double *xbt_graph_get_length_matrix(xbt_graph_t g)
300 unsigned int cursor = 0;
301 unsigned int in_cursor = 0;
302 unsigned long idx, i;
304 xbt_edge_t edge = NULL;
305 xbt_node_t node = NULL;
308 # define D(u,v) d[(u)*n+(v)]
309 n = xbt_dynar_length(g->nodes);
311 d = (double *) xbt_new0(double, n * n);
313 for (i = 0; i < n * n; i++) {
317 xbt_dynar_foreach(g->nodes, cursor, node) {
319 D(cursor, cursor) = 0;
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;
335 /** @brief Floyd-Warshall algorithm for shortest path finding
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).
347 void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d,
350 unsigned long i, j, k;
352 n = xbt_dynar_length(g->nodes);
354 # define D(u,v) d[(u)*n+(v)]
355 # define P(u,v) p[(u)*n+(v)]
357 for (i = 0; i < n * n; i++) {
362 for (i = 0; i < n; i++) {
363 for (j = 0; j < n; j++) {
365 P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i));
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);
389 /** @brief computes all-pairs shortest paths */
390 xbt_node_t *xbt_graph_shortest_paths(xbt_graph_t g)
394 unsigned long i, j, k;
400 # define P(u,v) p[(u)*n+(v)]
401 # define R(u,v) r[(u)*n+(v)]
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);
409 xbt_floyd_algorithm(g, adj, d, p);
411 for (i = 0; i < n; i++) {
412 for (j = 0; j < n; j++) {
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));
420 R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k));
433 /** @brief Extract a spanning tree of the given graph */
434 xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g)
437 int tree_size_max = xbt_dynar_length(g->nodes) - 1;
438 xbt_edge_t *tree = xbt_new0(xbt_edge_t, tree_size_max);
440 xbt_node_t node = NULL;
441 xbt_dynar_t edge_list = NULL;
442 xbt_heap_t heap = xbt_heap_new(10, NULL);
445 xbt_assert(!(g->directed),
446 "Spanning trees do not make sense on directed graphs");
448 xbt_dynar_foreach(g->nodes, cursor, node) {
449 node->xbtdata = NULL;
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));
458 while ((edge = xbt_heap_pop(heap))) {
459 if ((edge->src->xbtdata) && (edge->dst->xbtdata))
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));
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));
475 if (tree_size == tree_size_max)
484 /** @brief Topological sort on the given graph
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.
495 xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g)
504 n = xbt_dynar_length(g->nodes);
507 sorted = xbt_malloc(n * sizeof(xbt_node_t));
509 xbt_dynar_foreach(g->nodes, cursor, node)
510 node->xbtdata = xbt_new0(int, 1);
512 xbt_dynar_foreach(g->nodes, cursor, node)
513 xbt_graph_depth_visit(g, node, sorted, &idx);
515 xbt_dynar_foreach(g->nodes, cursor, node) {
517 node->xbtdata = NULL;
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)
530 if (*((int *) (n->xbtdata)) == ALREADY_EXPLORED)
532 else if (*((int *) (n->xbtdata)) == CURRENTLY_EXPLORING)
533 THROWF(0, 0, "There is a cycle");
535 *((int *) (n->xbtdata)) = CURRENTLY_EXPLORING;
537 xbt_dynar_foreach(n->out, cursor, edge) {
538 xbt_graph_depth_visit(g, edge->dst, sorted, idx);
541 *((int *) (n->xbtdata)) = ALREADY_EXPLORED;
542 sorted[(*idx)--] = n;
546 /********************* Import and Export ******************/
547 static xbt_graph_t parsed_graph = NULL;
548 static xbt_dict_t parsed_nodes = NULL;
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;
555 static void __parse_graph_begin(void)
557 XBT_DEBUG("<graph>");
558 if (A_graphxml_graph_isDirected == A_graphxml_graph_isDirected_true)
559 parsed_graph = xbt_graph_new_graph(1, NULL);
561 parsed_graph = xbt_graph_new_graph(0, NULL);
563 parsed_nodes = xbt_dict_new();
566 static void __parse_graph_end(void)
568 xbt_dict_free(&parsed_nodes);
569 XBT_DEBUG("</graph>");
572 static void __parse_node(void)
574 xbt_node_t node = xbt_graph_new_node(parsed_graph, NULL);
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 xbt_graph_parse_get_double(&(node->position_x),
581 A_graphxml_node_position_x);
582 xbt_graph_parse_get_double(&(node->position_y),
583 A_graphxml_node_position_y);
585 xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
588 static void __parse_edge(void)
590 xbt_edge_t edge = xbt_graph_new_edge(parsed_graph,
591 xbt_dict_get(parsed_nodes,
592 A_graphxml_edge_source),
593 xbt_dict_get(parsed_nodes,
594 A_graphxml_edge_target),
597 if (__parse_edge_label_and_data)
598 edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label,
599 A_graphxml_edge_data);
601 xbt_graph_parse_get_double(&(edge->length), A_graphxml_edge_length);
603 XBT_DEBUG("<edge source=\"%s\" target=\"%s\" length=\"%f\"/>",
604 (char *) (edge->src)->data,
605 (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge));
608 /** @brief Import a graph from a file following the GraphXML format */
609 xbt_graph_t xbt_graph_read(const char *filename,
610 void *(*node_label_and_data) (xbt_node_t,
613 void *(*edge_label_and_data) (xbt_edge_t,
618 xbt_graph_t graph = NULL;
620 __parse_node_label_and_data = node_label_and_data;
621 __parse_edge_label_and_data = edge_label_and_data;
623 xbt_graph_parse_reset_parser();
625 STag_graphxml_graph_fun = __parse_graph_begin;
626 ETag_graphxml_graph_fun = __parse_graph_end;
627 ETag_graphxml_node_fun = __parse_node;
628 ETag_graphxml_edge_fun = __parse_edge;
630 xbt_graph_parse_open(filename);
632 res = (*xbt_graph_parse) ();
633 xbt_assert(!res, "Parse error in %s", filename);
634 xbt_graph_parse_close();
636 graph = parsed_graph;
642 /** @brief Export the given graph in the GraphViz formatting for visualization */
643 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
644 const char *(node_name) (xbt_node_t),
645 const char *(edge_name) (xbt_edge_t))
647 unsigned int cursor = 0;
648 xbt_node_t node = NULL;
649 xbt_edge_t edge = NULL;
651 const char *name = NULL;
653 file = fopen(filename, "w");
654 xbt_assert(file, "Failed to open %s \n", filename);
657 fprintf(file, "digraph test {\n");
659 fprintf(file, "graph test {\n");
661 fprintf(file, " graph [overlap=scale]\n");
663 fprintf(file, " node [shape=box, style=filled]\n");
665 " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
667 xbt_dynar_foreach(g->nodes, cursor, node) {
668 fprintf(file, " \"%p\" ", node);
669 if ((node_name) && ((name = node_name(node))))
670 fprintf(file, "[label=\"%s\"]", name);
671 fprintf(file, ";\n");
673 xbt_dynar_foreach(g->edges, cursor, edge) {
675 fprintf(file, " \"%p\" -> \"%p\"", edge->src, edge->dst);
677 fprintf(file, " \"%p\" -- \"%p\"", edge->src, edge->dst);
678 if ((edge_name) && ((name = edge_name(edge))))
679 fprintf(file, "[label=\"%s\"]", name);
680 fprintf(file, ";\n");
682 fprintf(file, "}\n");
686 /** @brief Export the given graph in the GraphXML format */
687 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
688 const char *(node_name) (xbt_node_t),
689 const char *(edge_name) (xbt_edge_t),
690 const char *(node_data_print) (void *),
691 const char *(edge_data_print) (void *))
693 unsigned int cursor = 0;
694 xbt_node_t node = NULL;
695 xbt_edge_t edge = NULL;
697 const char *name = NULL;
699 file = fopen(filename, "w");
700 xbt_assert(file, "Failed to open %s \n", filename);
702 fprintf(file, "<?xml version='1.0'?>\n");
703 fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
705 fprintf(file, "<graph isDirected=\"true\">\n");
707 fprintf(file, "<graph isDirected=\"false\">\n");
708 xbt_dynar_foreach(g->nodes, cursor, node) {
709 fprintf(file, " <node name=\"%p\" ", node);
710 if ((node_name) && ((name = node_name(node))))
711 fprintf(file, "label=\"%s\" ", name);
712 if ((node_data_print) && ((name = node_data_print(node->data))))
713 fprintf(file, "data=\"%s\" ", name);
714 fprintf(file, ">\n");
716 xbt_dynar_foreach(g->edges, cursor, edge) {
717 fprintf(file, " <edge source=\"%p\" target =\"%p\" ",
718 edge->src, edge->dst);
719 if ((edge_name) && ((name = edge_name(edge))))
720 fprintf(file, "label=\"%s\" ", name);
721 if (edge->length >= 0.0)
722 fprintf(file, "length=\"%g\" ", edge->length);
723 if ((edge_data_print) && ((name = edge_data_print(edge->data))))
724 fprintf(file, "data=\"%s\" ", name);
725 fprintf(file, ">\n");
727 fprintf(file, "</graph>\n");
731 /** @brief Load a graph from a file (in the SimGrid Graph format) */
732 xbt_graph_t xbt_graph_load (const char *filename)
736 file = fopen (filename, "r");
737 xbt_assert(file, "Failed to open %s \n", filename);
739 xbt_dict_t nodes_dict = xbt_dict_new ();
740 xbt_graph_t ret = xbt_graph_new_graph (0, NULL);
742 //read the number of nodes
744 char *nnodes_str = NULL;
745 read = getline (&nnodes_str, &size, file);
746 int i, nnodes = atoi (nnodes_str);
750 for (i = 0; i < nnodes; i++){
751 char *node_str = NULL;
752 read = getline (&node_str, &size, file);
754 char *name = xbt_strdup (node_str);
755 xbt_str_subst (name, '\n', '\0', 0);
756 n = xbt_graph_new_node (ret, name);
757 xbt_dict_set (nodes_dict, name, n, NULL);
761 //read the number of edges
762 char *nedges_str = NULL;
763 read = getline (&nedges_str, &size, file);
764 int nedges = atoi (nedges_str);
768 for (i = 0; i < nedges; i++){
769 char *edge_str = NULL, edge_id[200], node_source[200], node_target[200];
770 read = getline (&edge_str, &size, file);
771 sscanf (edge_str, "%s %s %s", edge_id, node_source, node_target);
773 xbt_str_subst (edge_id, '\n', '\0', 0);
774 xbt_str_subst (node_source, '\n', '\0', 0);
775 xbt_str_subst (node_target, '\n', '\0', 0);
777 xbt_node_t source = xbt_dict_get (nodes_dict, node_source);
778 xbt_node_t target = xbt_dict_get (nodes_dict, node_target);
780 e = xbt_graph_new_edge (ret, source, target, xbt_strdup(edge_id));
782 xbt_dict_free (&nodes_dict);
786 /** @brief Save a graph from a file (in the SimGrid Graph format) */
787 void xbt_graph_save (xbt_graph_t span,
788 const char *filename,
789 const char *(nname) (xbt_node_t),
790 const char *(ename) (xbt_edge_t))
793 file = fopen(filename, "w");
794 xbt_assert(file, "Failed to open %s \n", filename);
796 xbt_dynar_t nodes = xbt_graph_get_nodes (span);
797 xbt_dynar_t edges = xbt_graph_get_edges (span);
800 fprintf (file, "%ld\n", xbt_dynar_length (nodes));
801 xbt_dynar_foreach (nodes, cpt, node) {
803 fprintf (file, "%s\n", nname(node));
805 fprintf (file, "%p\n", node);
808 fprintf (file, "%ld\n", xbt_dynar_length (edges));
810 xbt_dynar_foreach (edges, cpt, edge) {
811 xbt_node_t source = xbt_graph_edge_get_source (edge);
812 xbt_node_t target = xbt_graph_edge_get_target (edge);
815 fprintf (file, "%s %s %s\n", ename(edge), nname(source), nname(target));
817 fprintf (file, "%s %p %p\n", ename(edge), source, target);
821 fprintf (file, "%p %s %s\n", edge, nname(source), nname(target));
823 fprintf (file, "%p %p %p\n", edge, source, target);