1 /* a generic graph library. */
3 /* Copyright (c) 2006-2014. 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 "xbt/sysdep.h"
11 #include "xbt/graph.h"
12 #include "graph_private.h"
13 #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 /** @brief Get the edge connecting src and dst */
84 xbt_edge_t xbt_graph_get_edge(xbt_graph_t g, xbt_node_t src,
90 xbt_dynar_foreach(src->out, cursor, edge) {
91 XBT_DEBUG("%p = %p--%p", edge, edge->src, edge->dst);
92 if ((edge->src == src) && (edge->dst == dst))
96 xbt_dynar_foreach(src->out, cursor, edge) {
97 XBT_DEBUG("%p = %p--%p", edge, edge->src, edge->dst);
98 if ((edge->dst == src) && (edge->src == dst))
105 /** @brief Get the user data associated to a node */
106 void *xbt_graph_node_get_data(xbt_node_t node)
111 /** @brief Set the user data associated to a node */
112 void xbt_graph_node_set_data(xbt_node_t node, void *data)
117 /** @brief Get the user data associated to a edge */
118 void *xbt_graph_edge_get_data(xbt_edge_t edge)
123 /** @brief Set the user data associated to a edge */
124 void xbt_graph_edge_set_data(xbt_edge_t edge, void *data)
129 /** @brief Destructor
130 * @param g: poor victim
131 * @param node_free_function: function to use to free data associated to each node
132 * @param edge_free_function: function to use to free data associated to each edge
133 * @param graph_free_function: function to use to free data associated to g
135 * Free the graph structure.
137 void xbt_graph_free_graph(xbt_graph_t g,
138 void_f_pvoid_t node_free_function,
139 void_f_pvoid_t edge_free_function,
140 void_f_pvoid_t graph_free_function)
146 xbt_dynar_foreach(g->edges, cursor, edge) {
147 if (edge_free_function)
148 edge_free_function(edge->data);
151 xbt_dynar_free(&(g->edges));
153 xbt_dynar_foreach(g->nodes, cursor, node) {
154 xbt_dynar_free(&(node->out));
155 xbt_dynar_free(&(node->in));
156 if (node_free_function)
157 node_free_function(node->data);
160 xbt_dynar_free(&(g->nodes));
162 if (graph_free_function)
163 graph_free_function(g->data);
165 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 /** @brief Get the length of a edge */
289 double xbt_graph_edge_get_length(xbt_edge_t edge)
295 /** @brief construct the adjacency matrix corresponding to the given graph
297 * The weights are the distances between nodes
299 double *xbt_graph_get_length_matrix(xbt_graph_t g)
301 unsigned int cursor = 0;
302 unsigned int in_cursor = 0;
303 unsigned long idx, i;
305 xbt_edge_t edge = NULL;
306 xbt_node_t node = NULL;
309 # define D(u,v) d[(u)*n+(v)]
310 n = xbt_dynar_length(g->nodes);
312 d = (double *) xbt_new0(double, n * n);
314 for (i = 0; i < n * n; i++) {
318 xbt_dynar_foreach(g->nodes, cursor, node) {
320 D(cursor, cursor) = 0;
322 xbt_dynar_foreach(node->out, in_cursor, edge) {
323 if (edge->dst == node)
324 idx = __xbt_find_in_dynar(g->nodes, edge->src);
325 else /*case of undirected graphs */
326 idx = __xbt_find_in_dynar(g->nodes, edge->dst);
327 D(cursor, idx) = edge->length;
336 /** @brief Floyd-Warshall algorithm for shortest path finding
340 * The Floyd–Warshall algorithm takes as input an adjacency matrix
341 * representation of a weighted, directed graph (V, E). The weight of a
342 * path between two vertices is the sum of the weights of the edges along
343 * that path. The edges E of the graph may have negative weights, but the
344 * graph must not have any negative weight cycles. The algorithm computes,
345 * for each pair of vertices, the minimum weight among all paths between
346 * the two vertices. The running time complexity is Θ(|V|3).
348 void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d,
351 unsigned long i, j, k;
353 n = xbt_dynar_length(g->nodes);
355 # define D(u,v) d[(u)*n+(v)]
356 # define P(u,v) p[(u)*n+(v)]
358 for (i = 0; i < n * n; i++) {
363 for (i = 0; i < n; i++) {
364 for (j = 0; j < n; j++) {
366 P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i));
371 for (k = 0; k < n; k++) {
372 for (i = 0; i < n; i++) {
373 for (j = 0; j < n; j++) {
374 if ((D(i, k) != -1) && (D(k, j) != -1)) {
375 if ((D(i, j) == -1) || (D(i, j) > D(i, k) + D(k, j))) {
376 D(i, j) = D(i, k) + D(k, j);
390 /** @brief computes all-pairs shortest paths */
391 xbt_node_t *xbt_graph_shortest_paths(xbt_graph_t g)
395 unsigned long i, j, k;
401 # define P(u,v) p[(u)*n+(v)]
402 # define R(u,v) r[(u)*n+(v)]
404 n = xbt_dynar_length(g->nodes);
405 adj = xbt_graph_get_length_matrix(g);
406 d = xbt_new0(double, n * n);
407 p = xbt_new0(xbt_node_t, n * n);
408 r = xbt_new0(xbt_node_t, n * n);
410 xbt_floyd_algorithm(g, adj, d, p);
412 for (i = 0; i < n; i++) {
413 for (j = 0; j < n; j++) {
416 while ((P(i, k)) && (__xbt_find_in_dynar(g->nodes, P(i, k)) != i)) {
417 k = __xbt_find_in_dynar(g->nodes, P(i, k));
421 R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k));
434 /** @brief Extract a spanning tree of the given graph */
435 xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g)
438 int tree_size_max = xbt_dynar_length(g->nodes) - 1;
439 xbt_edge_t *tree = xbt_new0(xbt_edge_t, tree_size_max);
441 xbt_node_t node = NULL;
442 xbt_dynar_t edge_list = NULL;
443 xbt_heap_t heap = xbt_heap_new(10, NULL);
446 xbt_assert(!(g->directed),
447 "Spanning trees do not make sense on directed graphs");
449 xbt_dynar_foreach(g->nodes, cursor, node) {
450 node->xbtdata = NULL;
453 node = xbt_dynar_getfirst_as(g->nodes, xbt_node_t);
454 node->xbtdata = (void *) 1;
455 edge_list = node->out;
456 xbt_dynar_foreach(edge_list, cursor, e)
457 xbt_heap_push(heap, e, -(e->length));
459 while ((edge = xbt_heap_pop(heap))) {
460 if ((edge->src->xbtdata) && (edge->dst->xbtdata))
462 tree[tree_size++] = edge;
463 if (!(edge->src->xbtdata)) {
464 edge->src->xbtdata = (void *) 1;
465 edge_list = edge->src->out;
466 xbt_dynar_foreach(edge_list, cursor, e) {
467 xbt_heap_push(heap, e, -(e->length));
470 edge->dst->xbtdata = (void *) 1;
471 edge_list = edge->dst->out;
472 xbt_dynar_foreach(edge_list, cursor, e) {
473 xbt_heap_push(heap, e, -(e->length));
476 if (tree_size == tree_size_max)
485 /** @brief Topological sort on the given graph
489 * In graph theory, a topological sort of a directed acyclic graph (DAG) is
490 * a linear ordering of its nodes which is compatible with the partial
491 * order R induced on the nodes where x comes before y (xRy) if there's a
492 * directed path from x to y in the DAG. An equivalent definition is that
493 * each node comes before all nodes to which it has edges. Every DAG has at
494 * least one topological sort, and may have many.
496 xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g)
505 n = xbt_dynar_length(g->nodes);
508 sorted = xbt_malloc(n * sizeof(xbt_node_t));
510 xbt_dynar_foreach(g->nodes, cursor, node)
511 node->xbtdata = xbt_new0(int, 1);
513 xbt_dynar_foreach(g->nodes, cursor, node)
514 xbt_graph_depth_visit(g, node, sorted, &idx);
516 xbt_dynar_foreach(g->nodes, cursor, node) {
518 node->xbtdata = NULL;
524 /** @brief First-depth graph traversal */
525 void xbt_graph_depth_visit(xbt_graph_t g, xbt_node_t n,
526 xbt_node_t * sorted, int *idx)
531 if (*((int *) (n->xbtdata)) == ALREADY_EXPLORED)
533 else if (*((int *) (n->xbtdata)) == CURRENTLY_EXPLORING)
534 THROWF(0, 0, "There is a cycle");
536 *((int *) (n->xbtdata)) = CURRENTLY_EXPLORING;
538 xbt_dynar_foreach(n->out, cursor, edge) {
539 xbt_graph_depth_visit(g, edge->dst, sorted, idx);
542 *((int *) (n->xbtdata)) = ALREADY_EXPLORED;
543 sorted[(*idx)--] = n;
547 /********************* Import and Export ******************/
548 static xbt_graph_t parsed_graph = NULL;
549 static xbt_dict_t parsed_nodes = NULL;
551 static void *(*__parse_node_label_and_data) (xbt_node_t, const char *,
552 const char *) = NULL;
553 static void *(*__parse_edge_label_and_data) (xbt_edge_t, const char *,
554 const char *) = NULL;
556 static void __parse_graph_begin(void)
558 XBT_DEBUG("<graph>");
559 if (A_graphxml_graph_isDirected == A_graphxml_graph_isDirected_true)
560 parsed_graph = xbt_graph_new_graph(1, NULL);
562 parsed_graph = xbt_graph_new_graph(0, NULL);
564 parsed_nodes = xbt_dict_new_homogeneous(NULL);
567 static void __parse_graph_end(void)
569 xbt_dict_free(&parsed_nodes);
570 XBT_DEBUG("</graph>");
573 static void __parse_node(void)
575 xbt_node_t node = xbt_graph_new_node(parsed_graph, NULL);
577 XBT_DEBUG("<node name=\"%s\"/>", A_graphxml_node_name);
578 if (__parse_node_label_and_data)
579 node->data = __parse_node_label_and_data(node, A_graphxml_node_label,
580 A_graphxml_node_data);
581 node->position_x = xbt_graph_parse_get_double(A_graphxml_node_position___x);
582 node->position_y = xbt_graph_parse_get_double(A_graphxml_node_position___y);
584 xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
587 static void __parse_edge(void)
589 xbt_edge_t edge = xbt_graph_new_edge(parsed_graph,
590 xbt_dict_get(parsed_nodes,
591 A_graphxml_edge_source),
592 xbt_dict_get(parsed_nodes,
593 A_graphxml_edge_target),
596 if (__parse_edge_label_and_data)
597 edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label,
598 A_graphxml_edge_data);
600 edge->length = xbt_graph_parse_get_double(A_graphxml_edge_length);
602 XBT_DEBUG("<edge source=\"%s\" target=\"%s\" length=\"%f\"/>",
603 (char *) (edge->src)->data,
604 (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge));
607 /** @brief Import a graph from a file following the GraphXML format */
608 xbt_graph_t xbt_graph_read(const char *filename,
609 void *(*node_label_and_data) (xbt_node_t,
612 void *(*edge_label_and_data) (xbt_edge_t,
617 xbt_graph_t graph = NULL;
619 __parse_node_label_and_data = node_label_and_data;
620 __parse_edge_label_and_data = edge_label_and_data;
622 xbt_graph_parse_reset_parser();
624 STag_graphxml_graph_fun = __parse_graph_begin;
625 ETag_graphxml_graph_fun = __parse_graph_end;
626 ETag_graphxml_node_fun = __parse_node;
627 ETag_graphxml_edge_fun = __parse_edge;
629 xbt_graph_parse_open(filename);
630 XBT_ATTRIB_UNUSED int res;
631 res = xbt_graph_parse();
632 xbt_assert(!res, "Parse error in %s", filename);
633 xbt_graph_parse_close();
635 graph = parsed_graph;
641 /** @brief Export the given graph in the GraphViz formatting for visualization */
642 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
643 const char *(node_name) (xbt_node_t),
644 const char *(edge_name) (xbt_edge_t))
646 unsigned int cursor = 0;
647 xbt_node_t node = NULL;
648 xbt_edge_t edge = NULL;
650 const char *name = NULL;
652 file = fopen(filename, "w");
653 xbt_assert(file, "Failed to open %s \n", filename);
656 fprintf(file, "digraph test {\n");
658 fprintf(file, "graph test {\n");
660 fprintf(file, " graph [overlap=scale]\n");
662 fprintf(file, " node [shape=box, style=filled]\n");
664 " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
666 xbt_dynar_foreach(g->nodes, cursor, node) {
668 fprintf(file, " \"%s\";\n", node_name(node));
670 fprintf(file, " \"%p\";\n", node);
673 xbt_dynar_foreach(g->edges, cursor, edge) {
675 const char *c_dir = "->";
676 const char *c_ndir = "--";
682 const char *src_name, *dst_name;
684 src_name = node_name(edge->src);
685 dst_name = node_name(edge->dst);
686 fprintf(file, " \"%s\" %s \"%s\"", src_name, c, dst_name);
688 fprintf(file, " \"%p\" %s \"%p\"", edge->src, c, edge->dst);
691 if ((edge_name) && ((name = edge_name(edge))))
692 fprintf(file, "[label=\"%s\"]", name);
693 fprintf(file, ";\n");
695 fprintf(file, "}\n");
699 /** @brief Export the given graph in the GraphXML format */
700 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
701 const char *(node_name) (xbt_node_t),
702 const char *(edge_name) (xbt_edge_t),
703 const char *(node_data_print) (void *),
704 const char *(edge_data_print) (void *))
706 unsigned int cursor = 0;
707 xbt_node_t node = NULL;
708 xbt_edge_t edge = NULL;
710 const char *name = NULL;
712 file = fopen(filename, "w");
713 xbt_assert(file, "Failed to open %s \n", filename);
715 fprintf(file, "<?xml version='1.0'?>\n");
716 fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
718 fprintf(file, "<graph isDirected=\"true\">\n");
720 fprintf(file, "<graph isDirected=\"false\">\n");
721 xbt_dynar_foreach(g->nodes, cursor, node) {
722 fprintf(file, " <node name=\"%p\" ", node);
723 if ((node_name) && ((name = node_name(node))))
724 fprintf(file, "label=\"%s\" ", name);
725 if ((node_data_print) && ((name = node_data_print(node->data))))
726 fprintf(file, "data=\"%s\" ", name);
727 fprintf(file, "/>\n");
729 xbt_dynar_foreach(g->edges, cursor, edge) {
730 fprintf(file, " <edge source=\"%p\" target =\"%p\" ",
731 edge->src, edge->dst);
732 if ((edge_name) && ((name = edge_name(edge))))
733 fprintf(file, "label=\"%s\" ", name);
734 if (edge->length >= 0.0)
735 fprintf(file, "length=\"%g\" ", edge->length);
736 if ((edge_data_print) && ((name = edge_data_print(edge->data))))
737 fprintf(file, "data=\"%s\" ", name);
738 fprintf(file, "/>\n");
740 fprintf(file, "</graph>\n");
744 /** @brief Load a graph from a file (in the SimGrid Graph format) */
745 xbt_graph_t xbt_graph_load (const char *filename)
749 file = fopen (filename, "r");
750 xbt_assert(file, "Failed to open %s \n", filename);
752 xbt_dict_t nodes_dict = xbt_dict_new_homogeneous(NULL);
753 xbt_graph_t ret = xbt_graph_new_graph (0, NULL);
755 //read the number of nodes
757 char *nnodes_str = NULL;
758 read = xbt_getline (&nnodes_str, &size, file);
760 THROWF(system_error, 0, "xbt_getline failed to read the number of nodes (errno = %d)", errno);
761 int i, nnodes = atoi (nnodes_str);
765 for (i = 0; i < nnodes; i++){
766 char *node_str = NULL;
767 read = xbt_getline (&node_str, &size, file);
769 THROWF(system_error, 0, "xbt_getline failed to read all nodes (errno = %d)", errno);
771 char *name = xbt_strdup (node_str);
772 xbt_str_subst (name, '\n', '\0', 0);
773 n = xbt_graph_new_node (ret, name);
774 xbt_dict_set (nodes_dict, name, n, NULL);
778 //read the number of edges
779 char *nedges_str = NULL;
780 read = xbt_getline (&nedges_str, &size, file);
782 THROWF(system_error, 0, "xbt_getline failed to read the number of edges (errno = %d)", errno);
783 int nedges = atoi (nedges_str);
787 for (i = 0; i < nedges; i++){
788 char *edge_str = NULL, edge_id[200], node_source[200], node_target[200];
789 read = xbt_getline (&edge_str, &size, file);
791 THROWF(system_error, 0, "xbt_getline failed to read all edges (errno = %d)", errno);
792 sscanf (edge_str, "%s %s %s", edge_id, node_source, node_target);
794 xbt_str_subst (edge_id, '\n', '\0', 0);
795 xbt_str_subst (node_source, '\n', '\0', 0);
796 xbt_str_subst (node_target, '\n', '\0', 0);
798 xbt_node_t source = xbt_dict_get (nodes_dict, node_source);
799 xbt_node_t target = xbt_dict_get (nodes_dict, node_target);
800 xbt_graph_new_edge (ret, source, target, xbt_strdup(edge_id));
802 xbt_dict_free (&nodes_dict);
806 /** @brief Save a graph from a file (in the SimGrid Graph format) */
807 void xbt_graph_save (xbt_graph_t span,
808 const char *filename,
809 const char *(nname) (xbt_node_t),
810 const char *(ename) (xbt_edge_t))
813 file = fopen(filename, "w");
814 xbt_assert(file, "Failed to open %s \n", filename);
816 xbt_dynar_t nodes = xbt_graph_get_nodes (span);
817 xbt_dynar_t edges = xbt_graph_get_edges (span);
820 fprintf (file, "%lu\n", xbt_dynar_length (nodes));
821 xbt_dynar_foreach (nodes, cpt, node) {
823 fprintf (file, "%s\n", nname(node));
825 fprintf (file, "%p\n", node);
828 fprintf (file, "%lu\n", xbt_dynar_length (edges));
830 xbt_dynar_foreach (edges, cpt, edge) {
831 xbt_node_t source = xbt_graph_edge_get_source (edge);
832 xbt_node_t target = xbt_graph_edge_get_target (edge);
835 fprintf (file, "%s %s %s\n", ename(edge), nname(source), nname(target));
837 fprintf (file, "%s %p %p\n", ename(edge), source, target);
841 fprintf (file, "%p %s %s\n", edge, nname(source), nname(target));
843 fprintf (file, "%p %p %p\n", edge, source, target);