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 */
12 #include "xbt/sysdep.h"
14 #include "xbt/graph.h"
15 #include "graph_private.h"
16 #include "xbt/graphxml_parse.h"
24 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_graph, xbt, "Graph");
28 /** @brief Constructor
31 xbt_graph_t xbt_graph_new_graph(unsigned short int directed, void *data)
33 xbt_graph_t graph = NULL;
34 graph = xbt_new0(struct xbt_graph, 1);
35 graph->directed = directed;
37 graph->nodes = xbt_dynar_new(sizeof(xbt_node_t), NULL);
38 graph->edges = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
43 /** @brief add a node to the given graph */
44 xbt_node_t xbt_graph_new_node(xbt_graph_t g, void *data)
46 xbt_node_t node = NULL;
47 node = xbt_new0(struct xbt_node, 1);
50 /* only the "out" field is used */
51 node->in = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
53 node->out = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
54 node->position_x = -1.0;
55 node->position_y = -1.0;
57 xbt_dynar_push(g->nodes, &node);
62 /** @brief add an edge to the given graph */
63 xbt_edge_t xbt_graph_new_edge(xbt_graph_t g,
64 xbt_node_t src, xbt_node_t dst, void *data)
66 xbt_edge_t edge = NULL;
68 edge = xbt_new0(struct xbt_edge, 1);
69 xbt_dynar_push(src->out, &edge);
71 xbt_dynar_push(dst->in, &edge);
72 else /* only the "out" field is used */
73 xbt_dynar_push(dst->out, &edge);
79 xbt_dynar_push(g->edges, &edge);
84 /** @brief Get the edge connecting src and dst */
85 xbt_edge_t xbt_graph_get_edge(xbt_graph_t g, xbt_node_t src,
91 xbt_dynar_foreach(src->out, cursor, edge) {
92 XBT_DEBUG("%p = %p--%p", edge, edge->src, edge->dst);
93 if ((edge->src == src) && (edge->dst == dst))
97 xbt_dynar_foreach(src->out, cursor, edge) {
98 XBT_DEBUG("%p = %p--%p", edge, edge->src, edge->dst);
99 if ((edge->dst == src) && (edge->src == dst))
106 /** @brief Get the user data associated to a node */
107 void *xbt_graph_node_get_data(xbt_node_t node)
112 /** @brief Set the user data associated to a node */
113 void xbt_graph_node_set_data(xbt_node_t node, void *data)
118 /** @brief Get the user data associated to a edge */
119 void *xbt_graph_edge_get_data(xbt_edge_t edge)
124 /** @brief Set the user data associated to a edge */
125 void xbt_graph_edge_set_data(xbt_edge_t edge, void *data)
130 /** @brief Destructor
131 * @param g: poor victim
132 * @param node_free_function: function to use to free data associated to each node
133 * @param edge_free_function: function to use to free data associated to each edge
134 * @param graph_free_function: function to use to free data associated to g
136 * Free the graph structure.
138 void xbt_graph_free_graph(xbt_graph_t g,
139 void_f_pvoid_t node_free_function,
140 void_f_pvoid_t edge_free_function,
141 void_f_pvoid_t graph_free_function)
143 unsigned int cursor = 0;
144 xbt_node_t node = NULL;
145 xbt_edge_t edge = NULL;
148 xbt_dynar_foreach(g->nodes, cursor, node) {
149 xbt_dynar_free(&(node->out));
150 xbt_dynar_free(&(node->in));
151 if (node_free_function)
152 node_free_function(node->data);
155 xbt_dynar_foreach(g->edges, cursor, edge) {
156 if (edge_free_function)
157 edge_free_function(edge->data);
160 xbt_dynar_foreach(g->nodes, cursor, node)
162 xbt_dynar_free(&(g->nodes));
164 xbt_dynar_foreach(g->edges, cursor, edge)
166 xbt_dynar_free(&(g->edges));
167 if (graph_free_function)
168 graph_free_function(g->data);
170 xbt_graph_parse_lex_destroy();
175 /** @brief remove the given node from the given graph */
176 void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n,
177 void_f_pvoid_t node_free_function,
178 void_f_pvoid_t edge_free_function)
182 unsigned int cursor = 0;
183 xbt_node_t node = NULL;
184 xbt_edge_t edge = NULL;
186 nbr = xbt_dynar_length(g->edges);
188 for (i = 0; i < nbr; i++) {
189 xbt_dynar_get_cpy(g->edges, cursor, &edge);
191 if ((edge->dst == n) || (edge->src == n)) {
192 xbt_graph_free_edge(g, edge, edge_free_function);
197 if ((node_free_function) && (n->data))
198 node_free_function(n->data);
201 xbt_dynar_foreach(g->nodes, cursor, node)
203 xbt_dynar_cursor_rm(g->nodes, &cursor);
205 xbt_dynar_free(&(n->in));
206 xbt_dynar_free(&(n->out));
213 /** @brief remove the given edge from the given graph */
214 void xbt_graph_free_edge(xbt_graph_t g, xbt_edge_t e,
215 void_f_pvoid_t free_function)
218 unsigned int cursor = 0;
219 xbt_edge_t edge = NULL;
221 if ((free_function) && (e->data))
222 free_function(e->data);
224 xbt_dynar_foreach(g->edges, cursor, edge) {
227 idx = __xbt_find_in_dynar(edge->dst->in, edge);
228 xbt_dynar_remove_at(edge->dst->in, idx, NULL);
229 } else { /* only the out field is used */
230 idx = __xbt_find_in_dynar(edge->dst->out, edge);
231 xbt_dynar_remove_at(edge->dst->out, idx, NULL);
234 idx = __xbt_find_in_dynar(edge->src->out, edge);
235 xbt_dynar_remove_at(edge->src->out, idx, NULL);
237 xbt_dynar_cursor_rm(g->edges, &cursor);
244 int __xbt_find_in_dynar(xbt_dynar_t dynar, void *p)
247 unsigned int cursor = 0;
250 xbt_dynar_foreach(dynar, cursor, tmp) {
257 /** @brief Retrieve the graph's nodes as a dynar */
258 xbt_dynar_t xbt_graph_get_nodes(xbt_graph_t g)
263 /** @brief Retrieve the graph's edges as a dynar */
264 xbt_dynar_t xbt_graph_get_edges(xbt_graph_t g)
269 /** @brief Retrieve the node at the source of the given edge */
270 xbt_node_t xbt_graph_edge_get_source(xbt_edge_t e)
275 /** @brief Retrieve the node being the target of the given edge */
276 xbt_node_t xbt_graph_edge_get_target(xbt_edge_t e)
281 /** @brief Retrieve the outgoing edges of the given node */
282 xbt_dynar_t xbt_graph_node_get_outedges(xbt_node_t n)
287 /** @brief Set the weight of the given edge */
288 void xbt_graph_edge_set_length(xbt_edge_t e, double length)
294 /** @brief Get the length of a edge */
295 double xbt_graph_edge_get_length(xbt_edge_t edge)
301 /** @brief construct the adjacency matrix corresponding to the given graph
303 * The weights are the distances between nodes
305 double *xbt_graph_get_length_matrix(xbt_graph_t g)
307 unsigned int cursor = 0;
308 unsigned int in_cursor = 0;
309 unsigned long idx, i;
311 xbt_edge_t edge = NULL;
312 xbt_node_t node = NULL;
315 # define D(u,v) d[(u)*n+(v)]
316 n = xbt_dynar_length(g->nodes);
318 d = (double *) xbt_new0(double, n * n);
320 for (i = 0; i < n * n; i++) {
324 xbt_dynar_foreach(g->nodes, cursor, node) {
326 D(cursor, cursor) = 0;
328 xbt_dynar_foreach(node->out, in_cursor, edge) {
329 if (edge->dst == node)
330 idx = __xbt_find_in_dynar(g->nodes, edge->src);
331 else /*case of undirected graphs */
332 idx = __xbt_find_in_dynar(g->nodes, edge->dst);
333 D(cursor, idx) = edge->length;
342 /** @brief Floyd-Warshall algorithm for shortest path finding
346 * The Floyd–Warshall algorithm takes as input an adjacency matrix
347 * representation of a weighted, directed graph (V, E). The weight of a
348 * path between two vertices is the sum of the weights of the edges along
349 * that path. The edges E of the graph may have negative weights, but the
350 * graph must not have any negative weight cycles. The algorithm computes,
351 * for each pair of vertices, the minimum weight among all paths between
352 * the two vertices. The running time complexity is Θ(|V|3).
354 void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d,
357 unsigned long i, j, k;
359 n = xbt_dynar_length(g->nodes);
361 # define D(u,v) d[(u)*n+(v)]
362 # define P(u,v) p[(u)*n+(v)]
364 for (i = 0; i < n * n; i++) {
369 for (i = 0; i < n; i++) {
370 for (j = 0; j < n; j++) {
372 P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i));
377 for (k = 0; k < n; k++) {
378 for (i = 0; i < n; i++) {
379 for (j = 0; j < n; j++) {
380 if ((D(i, k) != -1) && (D(k, j) != -1)) {
381 if ((D(i, j) == -1) || (D(i, j) > D(i, k) + D(k, j))) {
382 D(i, j) = D(i, k) + D(k, j);
396 /** @brief computes all-pairs shortest paths */
397 xbt_node_t *xbt_graph_shortest_paths(xbt_graph_t g)
401 unsigned long i, j, k;
407 # define P(u,v) p[(u)*n+(v)]
408 # define R(u,v) r[(u)*n+(v)]
410 n = xbt_dynar_length(g->nodes);
411 adj = xbt_graph_get_length_matrix(g);
412 d = xbt_new0(double, n * n);
413 p = xbt_new0(xbt_node_t, n * n);
414 r = xbt_new0(xbt_node_t, n * n);
416 xbt_floyd_algorithm(g, adj, d, p);
418 for (i = 0; i < n; i++) {
419 for (j = 0; j < n; j++) {
422 while ((P(i, k)) && (__xbt_find_in_dynar(g->nodes, P(i, k)) != i)) {
423 k = __xbt_find_in_dynar(g->nodes, P(i, k));
427 R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k));
440 /** @brief Extract a spanning tree of the given graph */
441 xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g)
444 int tree_size_max = xbt_dynar_length(g->nodes) - 1;
445 xbt_edge_t *tree = xbt_new0(xbt_edge_t, tree_size_max);
447 xbt_node_t node = NULL;
448 xbt_dynar_t edge_list = NULL;
449 xbt_heap_t heap = xbt_heap_new(10, NULL);
452 xbt_assert(!(g->directed),
453 "Spanning trees do not make sense on directed graphs");
455 xbt_dynar_foreach(g->nodes, cursor, node) {
456 node->xbtdata = NULL;
459 node = xbt_dynar_getfirst_as(g->nodes, xbt_node_t);
460 node->xbtdata = (void *) 1;
461 edge_list = node->out;
462 xbt_dynar_foreach(edge_list, cursor, e)
463 xbt_heap_push(heap, e, -(e->length));
465 while ((edge = xbt_heap_pop(heap))) {
466 if ((edge->src->xbtdata) && (edge->dst->xbtdata))
468 tree[tree_size++] = edge;
469 if (!(edge->src->xbtdata)) {
470 edge->src->xbtdata = (void *) 1;
471 edge_list = edge->src->out;
472 xbt_dynar_foreach(edge_list, cursor, e) {
473 xbt_heap_push(heap, e, -(e->length));
476 edge->dst->xbtdata = (void *) 1;
477 edge_list = edge->dst->out;
478 xbt_dynar_foreach(edge_list, cursor, e) {
479 xbt_heap_push(heap, e, -(e->length));
482 if (tree_size == tree_size_max)
491 /** @brief Topological sort on the given graph
495 * In graph theory, a topological sort of a directed acyclic graph (DAG) is
496 * a linear ordering of its nodes which is compatible with the partial
497 * order R induced on the nodes where x comes before y (xRy) if there's a
498 * directed path from x to y in the DAG. An equivalent definition is that
499 * each node comes before all nodes to which it has edges. Every DAG has at
500 * least one topological sort, and may have many.
502 xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g)
511 n = xbt_dynar_length(g->nodes);
514 sorted = xbt_malloc(n * sizeof(xbt_node_t));
516 xbt_dynar_foreach(g->nodes, cursor, node)
517 node->xbtdata = xbt_new0(int, 1);
519 xbt_dynar_foreach(g->nodes, cursor, node)
520 xbt_graph_depth_visit(g, node, sorted, &idx);
522 xbt_dynar_foreach(g->nodes, cursor, node) {
524 node->xbtdata = NULL;
530 /** @brief First-depth graph traversal */
531 void xbt_graph_depth_visit(xbt_graph_t g, xbt_node_t n,
532 xbt_node_t * sorted, int *idx)
537 if (*((int *) (n->xbtdata)) == ALREADY_EXPLORED)
539 else if (*((int *) (n->xbtdata)) == CURRENTLY_EXPLORING)
540 THROWF(0, 0, "There is a cycle");
542 *((int *) (n->xbtdata)) = CURRENTLY_EXPLORING;
544 xbt_dynar_foreach(n->out, cursor, edge) {
545 xbt_graph_depth_visit(g, edge->dst, sorted, idx);
548 *((int *) (n->xbtdata)) = ALREADY_EXPLORED;
549 sorted[(*idx)--] = n;
553 /********************* Import and Export ******************/
554 static xbt_graph_t parsed_graph = NULL;
555 static xbt_dict_t parsed_nodes = NULL;
557 static void *(*__parse_node_label_and_data) (xbt_node_t, const char *,
558 const char *) = NULL;
559 static void *(*__parse_edge_label_and_data) (xbt_edge_t, const char *,
560 const char *) = NULL;
562 static void __parse_graph_begin(void)
564 XBT_DEBUG("<graph>");
565 if (A_graphxml_graph_isDirected == A_graphxml_graph_isDirected_true)
566 parsed_graph = xbt_graph_new_graph(1, NULL);
568 parsed_graph = xbt_graph_new_graph(0, NULL);
570 parsed_nodes = xbt_dict_new_homogeneous(NULL);
573 static void __parse_graph_end(void)
575 xbt_dict_free(&parsed_nodes);
576 XBT_DEBUG("</graph>");
579 static void __parse_node(void)
581 xbt_node_t node = xbt_graph_new_node(parsed_graph, NULL);
583 XBT_DEBUG("<node name=\"%s\"/>", A_graphxml_node_name);
584 if (__parse_node_label_and_data)
585 node->data = __parse_node_label_and_data(node, A_graphxml_node_label,
586 A_graphxml_node_data);
587 node->position_x = xbt_graph_parse_get_double(A_graphxml_node_position_x);
588 node->position_y = xbt_graph_parse_get_double(A_graphxml_node_position_y);
590 xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
593 static void __parse_edge(void)
595 xbt_edge_t edge = xbt_graph_new_edge(parsed_graph,
596 xbt_dict_get(parsed_nodes,
597 A_graphxml_edge_source),
598 xbt_dict_get(parsed_nodes,
599 A_graphxml_edge_target),
602 if (__parse_edge_label_and_data)
603 edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label,
604 A_graphxml_edge_data);
606 edge->length = xbt_graph_parse_get_double(A_graphxml_edge_length);
608 XBT_DEBUG("<edge source=\"%s\" target=\"%s\" length=\"%f\"/>",
609 (char *) (edge->src)->data,
610 (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge));
613 /** @brief Import a graph from a file following the GraphXML format */
614 xbt_graph_t xbt_graph_read(const char *filename,
615 void *(*node_label_and_data) (xbt_node_t,
618 void *(*edge_label_and_data) (xbt_edge_t,
623 xbt_graph_t graph = NULL;
625 __parse_node_label_and_data = node_label_and_data;
626 __parse_edge_label_and_data = edge_label_and_data;
628 xbt_graph_parse_reset_parser();
630 STag_graphxml_graph_fun = __parse_graph_begin;
631 ETag_graphxml_graph_fun = __parse_graph_end;
632 ETag_graphxml_node_fun = __parse_node;
633 ETag_graphxml_edge_fun = __parse_edge;
635 xbt_graph_parse_open(filename);
636 _XBT_GNUC_UNUSED int res;
637 res = xbt_graph_parse();
638 xbt_assert(!res, "Parse error in %s", filename);
639 xbt_graph_parse_close();
641 graph = parsed_graph;
647 /** @brief Export the given graph in the GraphViz formatting for visualization */
648 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
649 const char *(node_name) (xbt_node_t),
650 const char *(edge_name) (xbt_edge_t))
652 unsigned int cursor = 0;
653 xbt_node_t node = NULL;
654 xbt_edge_t edge = NULL;
656 const char *name = NULL;
658 file = fopen(filename, "w");
659 xbt_assert(file, "Failed to open %s \n", filename);
662 fprintf(file, "digraph test {\n");
664 fprintf(file, "graph test {\n");
666 fprintf(file, " graph [overlap=scale]\n");
668 fprintf(file, " node [shape=box, style=filled]\n");
670 " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
672 xbt_dynar_foreach(g->nodes, cursor, node) {
674 fprintf(file, " \"%s\";\n", node_name(node));
676 fprintf(file, " \"%p\";\n", node);
679 xbt_dynar_foreach(g->edges, cursor, edge) {
681 const char *c_dir = "->";
682 const char *c_ndir = "--";
688 const char *src_name, *dst_name;
690 src_name = node_name(edge->src);
691 dst_name = node_name(edge->dst);
692 fprintf(file, " \"%s\" %s \"%s\"", src_name, c, dst_name);
694 fprintf(file, " \"%p\" %s \"%p\"", edge->src, c, edge->dst);
697 if ((edge_name) && ((name = edge_name(edge))))
698 fprintf(file, "[label=\"%s\"]", name);
699 fprintf(file, ";\n");
701 fprintf(file, "}\n");
705 /** @brief Export the given graph in the GraphXML format */
706 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
707 const char *(node_name) (xbt_node_t),
708 const char *(edge_name) (xbt_edge_t),
709 const char *(node_data_print) (void *),
710 const char *(edge_data_print) (void *))
712 unsigned int cursor = 0;
713 xbt_node_t node = NULL;
714 xbt_edge_t edge = NULL;
716 const char *name = NULL;
718 file = fopen(filename, "w");
719 xbt_assert(file, "Failed to open %s \n", filename);
721 fprintf(file, "<?xml version='1.0'?>\n");
722 fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
724 fprintf(file, "<graph isDirected=\"true\">\n");
726 fprintf(file, "<graph isDirected=\"false\">\n");
727 xbt_dynar_foreach(g->nodes, cursor, node) {
728 fprintf(file, " <node name=\"%p\" ", node);
729 if ((node_name) && ((name = node_name(node))))
730 fprintf(file, "label=\"%s\" ", name);
731 if ((node_data_print) && ((name = node_data_print(node->data))))
732 fprintf(file, "data=\"%s\" ", name);
733 fprintf(file, ">\n");
735 xbt_dynar_foreach(g->edges, cursor, edge) {
736 fprintf(file, " <edge source=\"%p\" target =\"%p\" ",
737 edge->src, edge->dst);
738 if ((edge_name) && ((name = edge_name(edge))))
739 fprintf(file, "label=\"%s\" ", name);
740 if (edge->length >= 0.0)
741 fprintf(file, "length=\"%g\" ", edge->length);
742 if ((edge_data_print) && ((name = edge_data_print(edge->data))))
743 fprintf(file, "data=\"%s\" ", name);
744 fprintf(file, ">\n");
746 fprintf(file, "</graph>\n");
750 /** @brief Load a graph from a file (in the SimGrid Graph format) */
751 xbt_graph_t xbt_graph_load (const char *filename)
755 file = fopen (filename, "r");
756 xbt_assert(file, "Failed to open %s \n", filename);
758 xbt_dict_t nodes_dict = xbt_dict_new_homogeneous(NULL);
759 xbt_graph_t ret = xbt_graph_new_graph (0, NULL);
761 //read the number of nodes
763 char *nnodes_str = NULL;
764 read = getline (&nnodes_str, &size, file);
766 THROWF(system_error, 0, "getline failed to read the number of nodes (errno = %d)", errno);
767 int i, nnodes = atoi (nnodes_str);
771 for (i = 0; i < nnodes; i++){
772 char *node_str = NULL;
773 read = getline (&node_str, &size, file);
775 THROWF(system_error, 0, "getline failed to read all nodes (errno = %d)", errno);
777 char *name = xbt_strdup (node_str);
778 xbt_str_subst (name, '\n', '\0', 0);
779 n = xbt_graph_new_node (ret, name);
780 xbt_dict_set (nodes_dict, name, n, NULL);
784 //read the number of edges
785 char *nedges_str = NULL;
786 read = getline (&nedges_str, &size, file);
788 THROWF(system_error, 0, "getline failed to read the number of edges (errno = %d)", errno);
789 int nedges = atoi (nedges_str);
793 for (i = 0; i < nedges; i++){
794 char *edge_str = NULL, edge_id[200], node_source[200], node_target[200];
795 read = getline (&edge_str, &size, file);
797 THROWF(system_error, 0, "getline failed to read all edges (errno = %d)", errno);
798 sscanf (edge_str, "%s %s %s", edge_id, node_source, node_target);
800 xbt_str_subst (edge_id, '\n', '\0', 0);
801 xbt_str_subst (node_source, '\n', '\0', 0);
802 xbt_str_subst (node_target, '\n', '\0', 0);
804 xbt_node_t source = xbt_dict_get (nodes_dict, node_source);
805 xbt_node_t target = xbt_dict_get (nodes_dict, node_target);
806 xbt_graph_new_edge (ret, source, target, xbt_strdup(edge_id));
808 xbt_dict_free (&nodes_dict);
812 /** @brief Save a graph from a file (in the SimGrid Graph format) */
813 void xbt_graph_save (xbt_graph_t span,
814 const char *filename,
815 const char *(nname) (xbt_node_t),
816 const char *(ename) (xbt_edge_t))
819 file = fopen(filename, "w");
820 xbt_assert(file, "Failed to open %s \n", filename);
822 xbt_dynar_t nodes = xbt_graph_get_nodes (span);
823 xbt_dynar_t edges = xbt_graph_get_edges (span);
826 fprintf (file, "%lu\n", xbt_dynar_length (nodes));
827 xbt_dynar_foreach (nodes, cpt, node) {
829 fprintf (file, "%s\n", nname(node));
831 fprintf (file, "%p\n", node);
834 fprintf (file, "%lu\n", xbt_dynar_length (edges));
836 xbt_dynar_foreach (edges, cpt, edge) {
837 xbt_node_t source = xbt_graph_edge_get_source (edge);
838 xbt_node_t target = xbt_graph_edge_get_target (edge);
841 fprintf (file, "%s %s %s\n", ename(edge), nname(source), nname(target));
843 fprintf (file, "%s %p %p\n", ename(edge), source, target);
847 fprintf (file, "%p %s %s\n", edge, nname(source), nname(target));
849 fprintf (file, "%p %p %p\n", edge, source, target);