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 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 void *xbt_graph_node_get_data(xbt_node_t node)
110 void xbt_graph_node_set_data(xbt_node_t node, void *data)
115 void *xbt_graph_edge_get_data(xbt_edge_t edge)
120 void xbt_graph_edge_set_data(xbt_edge_t edge, void *data)
125 /** @brief Destructor
126 * @param g: poor victim
127 * @param node_free_function: function to use to free data associated to each node
128 * @param edge_free_function: function to use to free data associated to each edge
129 * @param graph_free_function: function to use to free data associated to g
131 * Free the graph structure.
133 void xbt_graph_free_graph(xbt_graph_t g,
134 void_f_pvoid_t node_free_function,
135 void_f_pvoid_t edge_free_function,
136 void_f_pvoid_t graph_free_function)
138 unsigned int cursor = 0;
139 xbt_node_t node = NULL;
140 xbt_edge_t edge = NULL;
143 xbt_dynar_foreach(g->nodes, cursor, node) {
144 xbt_dynar_free(&(node->out));
145 xbt_dynar_free(&(node->in));
146 if (node_free_function)
147 (*node_free_function) (node->data);
150 xbt_dynar_foreach(g->edges, cursor, edge) {
151 if (edge_free_function)
152 (*edge_free_function) (edge->data);
155 xbt_dynar_foreach(g->nodes, cursor, node)
157 xbt_dynar_free(&(g->nodes));
159 xbt_dynar_foreach(g->edges, cursor, edge)
161 xbt_dynar_free(&(g->edges));
162 if (graph_free_function)
163 (*graph_free_function) (g->data);
165 xbt_graph_parse_lex_destroy();
170 /** @brief remove the given node from the given graph */
171 void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n,
172 void_f_pvoid_t node_free_function,
173 void_f_pvoid_t edge_free_function)
177 unsigned int cursor = 0;
178 xbt_node_t node = NULL;
179 xbt_edge_t edge = NULL;
181 nbr = xbt_dynar_length(g->edges);
183 for (i = 0; i < nbr; i++) {
184 xbt_dynar_get_cpy(g->edges, cursor, &edge);
186 if ((edge->dst == n) || (edge->src == n)) {
187 xbt_graph_free_edge(g, edge, edge_free_function);
192 if ((node_free_function) && (n->data))
193 (*node_free_function) (n->data);
196 xbt_dynar_foreach(g->nodes, cursor, node)
198 xbt_dynar_cursor_rm(g->nodes, &cursor);
200 xbt_dynar_free(&(n->in));
201 xbt_dynar_free(&(n->out));
208 /** @brief remove the given edge from the given graph */
209 void xbt_graph_free_edge(xbt_graph_t g, xbt_edge_t e,
210 void_f_pvoid_t free_function)
213 unsigned int cursor = 0;
214 xbt_edge_t edge = NULL;
216 if ((free_function) && (e->data))
217 (*free_function) (e->data);
219 xbt_dynar_foreach(g->edges, cursor, edge) {
222 idx = __xbt_find_in_dynar(edge->dst->in, edge);
223 xbt_dynar_remove_at(edge->dst->in, idx, NULL);
224 } else { /* only the out field is used */
225 idx = __xbt_find_in_dynar(edge->dst->out, edge);
226 xbt_dynar_remove_at(edge->dst->out, idx, NULL);
229 idx = __xbt_find_in_dynar(edge->src->out, edge);
230 xbt_dynar_remove_at(edge->src->out, idx, NULL);
232 xbt_dynar_cursor_rm(g->edges, &cursor);
239 int __xbt_find_in_dynar(xbt_dynar_t dynar, void *p)
242 unsigned int cursor = 0;
245 xbt_dynar_foreach(dynar, cursor, tmp) {
252 /** @brief Retrieve the graph's nodes as a dynar */
253 xbt_dynar_t xbt_graph_get_nodes(xbt_graph_t g)
258 /** @brief Retrieve the graph's edges as a dynar */
259 xbt_dynar_t xbt_graph_get_edges(xbt_graph_t g)
264 /** @brief Retrieve the node at the source of the given edge */
265 xbt_node_t xbt_graph_edge_get_source(xbt_edge_t e)
270 /** @brief Retrieve the node being the target of the given edge */
271 xbt_node_t xbt_graph_edge_get_target(xbt_edge_t e)
276 /** @brief Retrieve the outgoing edges of the given node */
277 xbt_dynar_t xbt_graph_node_get_outedges(xbt_node_t n)
282 /** @brief Set the weight of the given edge */
283 void xbt_graph_edge_set_length(xbt_edge_t e, double length)
289 double xbt_graph_edge_get_length(xbt_edge_t e)
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();
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 xbt_graph_parse_get_double(&(node->position_x),
582 A_graphxml_node_position_x);
583 xbt_graph_parse_get_double(&(node->position_y),
584 A_graphxml_node_position_y);
586 xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
589 static void __parse_edge(void)
591 xbt_edge_t edge = xbt_graph_new_edge(parsed_graph,
592 xbt_dict_get(parsed_nodes,
593 A_graphxml_edge_source),
594 xbt_dict_get(parsed_nodes,
595 A_graphxml_edge_target),
598 if (__parse_edge_label_and_data)
599 edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label,
600 A_graphxml_edge_data);
602 xbt_graph_parse_get_double(&(edge->length), A_graphxml_edge_length);
604 XBT_DEBUG("<edge source=\"%s\" target=\"%s\" length=\"%f\"/>",
605 (char *) (edge->src)->data,
606 (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge));
609 /** @brief Import a graph from a file following the GraphXML format */
610 xbt_graph_t xbt_graph_read(const char *filename,
611 void *(*node_label_and_data) (xbt_node_t,
614 void *(*edge_label_and_data) (xbt_edge_t,
619 xbt_graph_t graph = NULL;
621 __parse_node_label_and_data = node_label_and_data;
622 __parse_edge_label_and_data = edge_label_and_data;
624 xbt_graph_parse_reset_parser();
626 STag_graphxml_graph_fun = __parse_graph_begin;
627 ETag_graphxml_graph_fun = __parse_graph_end;
628 ETag_graphxml_node_fun = __parse_node;
629 ETag_graphxml_edge_fun = __parse_edge;
631 xbt_graph_parse_open(filename);
633 res = (*xbt_graph_parse) ();
634 xbt_assert(!res, "Parse error in %s", filename);
635 xbt_graph_parse_close();
637 graph = parsed_graph;
643 /** @brief Export the given graph in the GraphViz formatting for visualization */
644 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
645 const char *(node_name) (xbt_node_t),
646 const char *(edge_name) (xbt_edge_t))
648 unsigned int cursor = 0;
649 xbt_node_t node = NULL;
650 xbt_edge_t edge = NULL;
652 const char *name = NULL;
654 file = fopen(filename, "w");
655 xbt_assert(file, "Failed to open %s \n", filename);
658 fprintf(file, "digraph test {\n");
660 fprintf(file, "graph test {\n");
662 fprintf(file, " graph [overlap=scale]\n");
664 fprintf(file, " node [shape=box, style=filled]\n");
666 " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
668 xbt_dynar_foreach(g->nodes, cursor, node) {
669 fprintf(file, " \"%p\" ", node);
670 if ((node_name) && ((name = node_name(node))))
671 fprintf(file, "[label=\"%s\"]", name);
672 fprintf(file, ";\n");
674 xbt_dynar_foreach(g->edges, cursor, edge) {
676 fprintf(file, " \"%p\" -> \"%p\"", edge->src, edge->dst);
678 fprintf(file, " \"%p\" -- \"%p\"", edge->src, edge->dst);
679 if ((edge_name) && ((name = edge_name(edge))))
680 fprintf(file, "[label=\"%s\"]", name);
681 fprintf(file, ";\n");
683 fprintf(file, "}\n");
687 /** @brief Export the given graph in the GraphXML format */
688 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
689 const char *(node_name) (xbt_node_t),
690 const char *(edge_name) (xbt_edge_t),
691 const char *(node_data_print) (void *),
692 const char *(edge_data_print) (void *))
694 unsigned int cursor = 0;
695 xbt_node_t node = NULL;
696 xbt_edge_t edge = NULL;
698 const char *name = NULL;
700 file = fopen(filename, "w");
701 xbt_assert(file, "Failed to open %s \n", filename);
703 fprintf(file, "<?xml version='1.0'?>\n");
704 fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
706 fprintf(file, "<graph isDirected=\"true\">\n");
708 fprintf(file, "<graph isDirected=\"false\">\n");
709 xbt_dynar_foreach(g->nodes, cursor, node) {
710 fprintf(file, " <node name=\"%p\" ", node);
711 if ((node_name) && ((name = node_name(node))))
712 fprintf(file, "label=\"%s\" ", name);
713 if ((node_data_print) && ((name = node_data_print(node->data))))
714 fprintf(file, "data=\"%s\" ", name);
715 fprintf(file, ">\n");
717 xbt_dynar_foreach(g->edges, cursor, edge) {
718 fprintf(file, " <edge source=\"%p\" target =\"%p\" ",
719 edge->src, edge->dst);
720 if ((edge_name) && ((name = edge_name(edge))))
721 fprintf(file, "label=\"%s\" ", name);
722 if (edge->length >= 0.0)
723 fprintf(file, "length=\"%g\" ", edge->length);
724 if ((edge_data_print) && ((name = edge_data_print(edge->data))))
725 fprintf(file, "data=\"%s\" ", name);
726 fprintf(file, ">\n");
728 fprintf(file, "</graph>\n");
732 /** @brief Load a graph from a file (in the SimGrid Graph format) */
733 xbt_graph_t xbt_graph_load (const char *filename)
737 file = fopen (filename, "r");
738 xbt_assert(file, "Failed to open %s \n", filename);
740 xbt_dict_t nodes_dict = xbt_dict_new ();
741 xbt_graph_t ret = xbt_graph_new_graph (0, NULL);
743 //read the number of nodes
745 char *nnodes_str = NULL;
746 read = getline (&nnodes_str, &size, file);
748 THROWF(system_error, 0, "getline failed to read the number of nodes (errno = %d)", errno);
749 int i, nnodes = atoi (nnodes_str);
753 for (i = 0; i < nnodes; i++){
754 char *node_str = NULL;
755 read = getline (&node_str, &size, file);
757 THROWF(system_error, 0, "getline failed to read all nodes (errno = %d)", errno);
759 char *name = xbt_strdup (node_str);
760 xbt_str_subst (name, '\n', '\0', 0);
761 n = xbt_graph_new_node (ret, name);
762 xbt_dict_set (nodes_dict, name, n, NULL);
766 //read the number of edges
767 char *nedges_str = NULL;
768 read = getline (&nedges_str, &size, file);
770 THROWF(system_error, 0, "getline failed to read the number of edges (errno = %d)", errno);
771 int nedges = atoi (nedges_str);
775 for (i = 0; i < nedges; i++){
776 char *edge_str = NULL, edge_id[200], node_source[200], node_target[200];
777 read = getline (&edge_str, &size, file);
779 THROWF(system_error, 0, "getline failed to read all edges (errno = %d)", errno);
780 sscanf (edge_str, "%s %s %s", edge_id, node_source, node_target);
782 xbt_str_subst (edge_id, '\n', '\0', 0);
783 xbt_str_subst (node_source, '\n', '\0', 0);
784 xbt_str_subst (node_target, '\n', '\0', 0);
786 xbt_node_t source = xbt_dict_get (nodes_dict, node_source);
787 xbt_node_t target = xbt_dict_get (nodes_dict, node_target);
788 xbt_graph_new_edge (ret, source, target, xbt_strdup(edge_id));
790 xbt_dict_free (&nodes_dict);
794 /** @brief Save a graph from a file (in the SimGrid Graph format) */
795 void xbt_graph_save (xbt_graph_t span,
796 const char *filename,
797 const char *(nname) (xbt_node_t),
798 const char *(ename) (xbt_edge_t))
801 file = fopen(filename, "w");
802 xbt_assert(file, "Failed to open %s \n", filename);
804 xbt_dynar_t nodes = xbt_graph_get_nodes (span);
805 xbt_dynar_t edges = xbt_graph_get_edges (span);
808 fprintf (file, "%ld\n", xbt_dynar_length (nodes));
809 xbt_dynar_foreach (nodes, cpt, node) {
811 fprintf (file, "%s\n", nname(node));
813 fprintf (file, "%p\n", node);
816 fprintf (file, "%ld\n", xbt_dynar_length (edges));
818 xbt_dynar_foreach (edges, cpt, edge) {
819 xbt_node_t source = xbt_graph_edge_get_source (edge);
820 xbt_node_t target = xbt_graph_edge_get_target (edge);
823 fprintf (file, "%s %s %s\n", ename(edge), nname(source), nname(target));
825 fprintf (file, "%s %p %p\n", ename(edge), source, target);
829 fprintf (file, "%p %s %s\n", edge, nname(source), nname(target));
831 fprintf (file, "%p %p %p\n", edge, source, target);