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"
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_graph, xbt, "Graph");
26 /** @brief Constructor
29 xbt_graph_t xbt_graph_new_graph(unsigned short int directed, void *data)
31 xbt_graph_t graph = NULL;
32 graph = xbt_new0(struct xbt_graph, 1);
33 graph->directed = directed;
35 graph->nodes = xbt_dynar_new(sizeof(xbt_node_t), NULL);
36 graph->edges = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
41 /** @brief add a node to the given graph */
42 xbt_node_t xbt_graph_new_node(xbt_graph_t g, void *data)
44 xbt_node_t node = NULL;
45 node = xbt_new0(struct xbt_node, 1);
48 /* only the "out" field is used */
49 node->in = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
51 node->out = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
52 node->position_x = -1.0;
53 node->position_y = -1.0;
55 xbt_dynar_push(g->nodes, &node);
60 /** @brief add an edge to the given graph */
61 xbt_edge_t xbt_graph_new_edge(xbt_graph_t g,
62 xbt_node_t src, xbt_node_t dst, void *data)
64 xbt_edge_t edge = NULL;
66 edge = xbt_new0(struct xbt_edge, 1);
67 xbt_dynar_push(src->out, &edge);
69 xbt_dynar_push(dst->in, &edge);
70 else /* only the "out" field is used */
71 xbt_dynar_push(dst->out, &edge);
77 xbt_dynar_push(g->edges, &edge);
82 /** @brief Get the edge connecting src and dst */
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 /** @brief Get the user data associated to a node */
105 void *xbt_graph_node_get_data(xbt_node_t node)
110 /** @brief Set the user data associated to a node */
111 void xbt_graph_node_set_data(xbt_node_t node, void *data)
116 /** @brief Get the user data associated to a edge */
117 void *xbt_graph_edge_get_data(xbt_edge_t edge)
122 /** @brief Set the user data associated to a edge */
123 void xbt_graph_edge_set_data(xbt_edge_t edge, void *data)
128 /** @brief Destructor
129 * @param g: poor victim
130 * @param node_free_function: function to use to free data associated to each node
131 * @param edge_free_function: function to use to free data associated to each edge
132 * @param graph_free_function: function to use to free data associated to g
134 * Free the graph structure.
136 void xbt_graph_free_graph(xbt_graph_t g,
137 void_f_pvoid_t node_free_function,
138 void_f_pvoid_t edge_free_function,
139 void_f_pvoid_t graph_free_function)
145 xbt_dynar_foreach(g->edges, cursor, edge) {
146 if (edge_free_function)
147 edge_free_function(edge->data);
150 xbt_dynar_free(&(g->edges));
152 xbt_dynar_foreach(g->nodes, cursor, node) {
153 xbt_dynar_free(&(node->out));
154 xbt_dynar_free(&(node->in));
155 if (node_free_function)
156 node_free_function(node->data);
159 xbt_dynar_free(&(g->nodes));
161 if (graph_free_function)
162 graph_free_function(g->data);
167 /** @brief remove the given node from the given graph */
168 void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n,
169 void_f_pvoid_t node_free_function,
170 void_f_pvoid_t edge_free_function)
174 unsigned int cursor = 0;
175 xbt_node_t node = NULL;
176 xbt_edge_t edge = NULL;
178 nbr = xbt_dynar_length(g->edges);
180 for (i = 0; i < nbr; i++) {
181 xbt_dynar_get_cpy(g->edges, cursor, &edge);
183 if ((edge->dst == n) || (edge->src == n)) {
184 xbt_graph_free_edge(g, edge, edge_free_function);
189 if ((node_free_function) && (n->data))
190 node_free_function(n->data);
193 xbt_dynar_foreach(g->nodes, cursor, node)
195 xbt_dynar_cursor_rm(g->nodes, &cursor);
197 xbt_dynar_free(&(n->in));
198 xbt_dynar_free(&(n->out));
205 /** @brief remove the given edge from the given graph */
206 void xbt_graph_free_edge(xbt_graph_t g, xbt_edge_t e,
207 void_f_pvoid_t free_function)
210 unsigned int cursor = 0;
211 xbt_edge_t edge = NULL;
213 if ((free_function) && (e->data))
214 free_function(e->data);
216 xbt_dynar_foreach(g->edges, cursor, edge) {
219 idx = __xbt_find_in_dynar(edge->dst->in, edge);
220 xbt_dynar_remove_at(edge->dst->in, idx, NULL);
221 } else { /* only the out field is used */
222 idx = __xbt_find_in_dynar(edge->dst->out, edge);
223 xbt_dynar_remove_at(edge->dst->out, idx, NULL);
226 idx = __xbt_find_in_dynar(edge->src->out, edge);
227 xbt_dynar_remove_at(edge->src->out, idx, NULL);
229 xbt_dynar_cursor_rm(g->edges, &cursor);
236 int __xbt_find_in_dynar(xbt_dynar_t dynar, void *p)
239 unsigned int cursor = 0;
242 xbt_dynar_foreach(dynar, cursor, tmp) {
249 /** @brief Retrieve the graph's nodes as a dynar */
250 xbt_dynar_t xbt_graph_get_nodes(xbt_graph_t g)
255 /** @brief Retrieve the graph's edges as a dynar */
256 xbt_dynar_t xbt_graph_get_edges(xbt_graph_t g)
261 /** @brief Retrieve the node at the source of the given edge */
262 xbt_node_t xbt_graph_edge_get_source(xbt_edge_t e)
267 /** @brief Retrieve the node being the target of the given edge */
268 xbt_node_t xbt_graph_edge_get_target(xbt_edge_t e)
273 /** @brief Retrieve the outgoing edges of the given node */
274 xbt_dynar_t xbt_graph_node_get_outedges(xbt_node_t n)
279 /** @brief Set the weight of the given edge */
280 void xbt_graph_edge_set_length(xbt_edge_t e, double length)
286 /** @brief Get the length of a edge */
287 double xbt_graph_edge_get_length(xbt_edge_t edge)
293 /** @brief construct the adjacency matrix corresponding to the given graph
295 * The weights are the distances between nodes
297 double *xbt_graph_get_length_matrix(xbt_graph_t g)
299 unsigned int cursor = 0;
300 unsigned int in_cursor = 0;
301 unsigned long idx, i;
303 xbt_edge_t edge = NULL;
304 xbt_node_t node = NULL;
307 # define D(u,v) d[(u)*n+(v)]
308 n = xbt_dynar_length(g->nodes);
310 d = (double *) xbt_new0(double, n * n);
312 for (i = 0; i < n * n; i++) {
316 xbt_dynar_foreach(g->nodes, cursor, node) {
317 D(cursor, cursor) = 0;
319 xbt_dynar_foreach(node->out, in_cursor, edge) {
320 if (edge->dst == node)
321 idx = __xbt_find_in_dynar(g->nodes, edge->src);
322 else /*case of undirected graphs */
323 idx = __xbt_find_in_dynar(g->nodes, edge->dst);
324 D(cursor, idx) = edge->length;
333 /** @brief Floyd-Warshall algorithm for shortest path finding
337 * The Floyd–Warshall algorithm takes as input an adjacency matrix
338 * representation of a weighted, directed graph (V, E). The weight of a
339 * path between two vertices is the sum of the weights of the edges along
340 * that path. The edges E of the graph may have negative weights, but the
341 * graph must not have any negative weight cycles. The algorithm computes,
342 * for each pair of vertices, the minimum weight among all paths between
343 * the two vertices. The running time complexity is Θ(|V|3).
345 void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d,
348 unsigned long i, j, k;
350 n = xbt_dynar_length(g->nodes);
352 # define D(u,v) d[(u)*n+(v)]
353 # define P(u,v) p[(u)*n+(v)]
355 for (i = 0; i < n * n; i++) {
360 for (i = 0; i < n; i++) {
361 for (j = 0; j < n; j++) {
363 P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i));
368 for (k = 0; k < n; k++) {
369 for (i = 0; i < n; i++) {
370 for (j = 0; j < n; j++) {
371 if ((D(i, k) != -1) && (D(k, j) != -1)) {
372 if ((D(i, j) == -1) || (D(i, j) > D(i, k) + D(k, j))) {
373 D(i, j) = D(i, k) + D(k, j);
387 /** @brief computes all-pairs shortest paths */
388 xbt_node_t *xbt_graph_shortest_paths(xbt_graph_t g)
392 unsigned long i, j, k;
398 # define P(u,v) p[(u)*n+(v)]
399 # define R(u,v) r[(u)*n+(v)]
401 n = xbt_dynar_length(g->nodes);
402 adj = xbt_graph_get_length_matrix(g);
403 d = xbt_new0(double, n * n);
404 p = xbt_new0(xbt_node_t, n * n);
405 r = xbt_new0(xbt_node_t, n * n);
407 xbt_floyd_algorithm(g, adj, d, p);
409 for (i = 0; i < n; i++) {
410 for (j = 0; j < n; j++) {
413 while ((P(i, k)) && (__xbt_find_in_dynar(g->nodes, P(i, k)) != i)) {
414 k = __xbt_find_in_dynar(g->nodes, P(i, k));
418 R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k));
431 /** @brief Extract a spanning tree of the given graph */
432 xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g)
435 int tree_size_max = xbt_dynar_length(g->nodes) - 1;
436 xbt_edge_t *tree = xbt_new0(xbt_edge_t, tree_size_max);
438 xbt_node_t node = NULL;
439 xbt_dynar_t edge_list = NULL;
440 xbt_heap_t heap = xbt_heap_new(10, NULL);
443 xbt_assert(!(g->directed),
444 "Spanning trees do not make sense on directed graphs");
446 xbt_dynar_foreach(g->nodes, cursor, node) {
447 node->xbtdata = NULL;
450 node = xbt_dynar_getfirst_as(g->nodes, xbt_node_t);
451 node->xbtdata = (void *) 1;
452 edge_list = node->out;
453 xbt_dynar_foreach(edge_list, cursor, e)
454 xbt_heap_push(heap, e, -(e->length));
456 while ((edge = xbt_heap_pop(heap))) {
457 if ((edge->src->xbtdata) && (edge->dst->xbtdata))
459 tree[tree_size++] = edge;
460 if (!(edge->src->xbtdata)) {
461 edge->src->xbtdata = (void *) 1;
462 edge_list = edge->src->out;
463 xbt_dynar_foreach(edge_list, cursor, e) {
464 xbt_heap_push(heap, e, -(e->length));
467 edge->dst->xbtdata = (void *) 1;
468 edge_list = edge->dst->out;
469 xbt_dynar_foreach(edge_list, cursor, e) {
470 xbt_heap_push(heap, e, -(e->length));
473 if (tree_size == tree_size_max)
482 /** @brief Topological sort on the given graph
486 * In graph theory, a topological sort of a directed acyclic graph (DAG) is
487 * a linear ordering of its nodes which is compatible with the partial
488 * order R induced on the nodes where x comes before y (xRy) if there's a
489 * directed path from x to y in the DAG. An equivalent definition is that
490 * each node comes before all nodes to which it has edges. Every DAG has at
491 * least one topological sort, and may have many.
493 xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g)
502 n = xbt_dynar_length(g->nodes);
505 sorted = xbt_malloc(n * sizeof(xbt_node_t));
507 xbt_dynar_foreach(g->nodes, cursor, node)
508 node->xbtdata = xbt_new0(int, 1);
510 xbt_dynar_foreach(g->nodes, cursor, node)
511 xbt_graph_depth_visit(g, node, sorted, &idx);
513 xbt_dynar_foreach(g->nodes, cursor, node) {
515 node->xbtdata = NULL;
521 /** @brief First-depth graph traversal */
522 void xbt_graph_depth_visit(xbt_graph_t g, xbt_node_t n,
523 xbt_node_t * sorted, int *idx)
528 if (*((int *) (n->xbtdata)) == ALREADY_EXPLORED)
530 else if (*((int *) (n->xbtdata)) == CURRENTLY_EXPLORING)
531 THROWF(0, 0, "There is a cycle");
533 *((int *) (n->xbtdata)) = CURRENTLY_EXPLORING;
535 xbt_dynar_foreach(n->out, cursor, edge) {
536 xbt_graph_depth_visit(g, edge->dst, sorted, idx);
539 *((int *) (n->xbtdata)) = ALREADY_EXPLORED;
540 sorted[(*idx)--] = n;
544 /** @brief Export the given graph in the GraphViz formatting for visualization */
545 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
546 const char *(node_name) (xbt_node_t),
547 const char *(edge_name) (xbt_edge_t))
549 unsigned int cursor = 0;
550 xbt_node_t node = NULL;
551 xbt_edge_t edge = NULL;
553 const char *name = NULL;
555 file = fopen(filename, "w");
556 xbt_assert(file, "Failed to open %s \n", filename);
559 fprintf(file, "digraph test {\n");
561 fprintf(file, "graph test {\n");
563 fprintf(file, " graph [overlap=scale]\n");
565 fprintf(file, " node [shape=box, style=filled]\n");
567 " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
569 xbt_dynar_foreach(g->nodes, cursor, node) {
571 fprintf(file, " \"%s\";\n", node_name(node));
573 fprintf(file, " \"%p\";\n", node);
576 xbt_dynar_foreach(g->edges, cursor, edge) {
578 const char *c_dir = "->";
579 const char *c_ndir = "--";
585 const char *src_name, *dst_name;
587 src_name = node_name(edge->src);
588 dst_name = node_name(edge->dst);
589 fprintf(file, " \"%s\" %s \"%s\"", src_name, c, dst_name);
591 fprintf(file, " \"%p\" %s \"%p\"", edge->src, c, edge->dst);
594 if ((edge_name) && ((name = edge_name(edge))))
595 fprintf(file, "[label=\"%s\"]", name);
596 fprintf(file, ";\n");
598 fprintf(file, "}\n");
602 /** @brief Export the given graph in the GraphXML format */
603 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
604 const char *(node_name) (xbt_node_t),
605 const char *(edge_name) (xbt_edge_t),
606 const char *(node_data_print) (void *),
607 const char *(edge_data_print) (void *))
609 unsigned int cursor = 0;
610 xbt_node_t node = NULL;
611 xbt_edge_t edge = NULL;
613 const char *name = NULL;
615 file = fopen(filename, "w");
616 xbt_assert(file, "Failed to open %s \n", filename);
618 fprintf(file, "<?xml version='1.0'?>\n");
619 fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
621 fprintf(file, "<graph isDirected=\"true\">\n");
623 fprintf(file, "<graph isDirected=\"false\">\n");
624 xbt_dynar_foreach(g->nodes, cursor, node) {
625 fprintf(file, " <node name=\"%p\" ", node);
626 if ((node_name) && ((name = node_name(node))))
627 fprintf(file, "label=\"%s\" ", name);
628 if ((node_data_print) && ((name = node_data_print(node->data))))
629 fprintf(file, "data=\"%s\" ", name);
630 fprintf(file, "/>\n");
632 xbt_dynar_foreach(g->edges, cursor, edge) {
633 fprintf(file, " <edge source=\"%p\" target =\"%p\" ",
634 edge->src, edge->dst);
635 if ((edge_name) && ((name = edge_name(edge))))
636 fprintf(file, "label=\"%s\" ", name);
637 if (edge->length >= 0.0)
638 fprintf(file, "length=\"%g\" ", edge->length);
639 if ((edge_data_print) && ((name = edge_data_print(edge->data))))
640 fprintf(file, "data=\"%s\" ", name);
641 fprintf(file, "/>\n");
643 fprintf(file, "</graph>\n");
647 /** @brief Load a graph from a file (in the SimGrid Graph format) */
648 xbt_graph_t xbt_graph_load (const char *filename)
652 file = fopen (filename, "r");
653 xbt_assert(file, "Failed to open %s \n", filename);
655 xbt_dict_t nodes_dict = xbt_dict_new_homogeneous(NULL);
656 xbt_graph_t ret = xbt_graph_new_graph (0, NULL);
658 //read the number of nodes
660 char *nnodes_str = NULL;
661 read = xbt_getline (&nnodes_str, &size, file);
663 THROWF(system_error, 0, "xbt_getline failed to read the number of nodes (errno = %d)", errno);
664 int i, nnodes = atoi (nnodes_str);
668 for (i = 0; i < nnodes; i++){
669 char *node_str = NULL;
670 read = xbt_getline (&node_str, &size, file);
672 THROWF(system_error, 0, "xbt_getline failed to read all nodes (errno = %d)", errno);
674 char *name = xbt_strdup (node_str);
675 xbt_str_subst (name, '\n', '\0', 0);
676 n = xbt_graph_new_node (ret, name);
677 xbt_dict_set (nodes_dict, name, n, NULL);
681 //read the number of edges
682 char *nedges_str = NULL;
683 read = xbt_getline (&nedges_str, &size, file);
685 THROWF(system_error, 0, "xbt_getline failed to read the number of edges (errno = %d)", errno);
686 int nedges = atoi (nedges_str);
690 for (i = 0; i < nedges; i++){
691 char *edge_str = NULL, edge_id[200], node_source[200], node_target[200];
692 read = xbt_getline (&edge_str, &size, file);
694 THROWF(system_error, 0, "xbt_getline failed to read all edges (errno = %d)", errno);
695 sscanf (edge_str, "%s %s %s", edge_id, node_source, node_target);
697 xbt_str_subst (edge_id, '\n', '\0', 0);
698 xbt_str_subst (node_source, '\n', '\0', 0);
699 xbt_str_subst (node_target, '\n', '\0', 0);
701 xbt_node_t source = xbt_dict_get (nodes_dict, node_source);
702 xbt_node_t target = xbt_dict_get (nodes_dict, node_target);
703 xbt_graph_new_edge (ret, source, target, xbt_strdup(edge_id));
705 xbt_dict_free (&nodes_dict);
709 /** @brief Save a graph from a file (in the SimGrid Graph format) */
710 void xbt_graph_save (xbt_graph_t span,
711 const char *filename,
712 const char *(nname) (xbt_node_t),
713 const char *(ename) (xbt_edge_t))
716 file = fopen(filename, "w");
717 xbt_assert(file, "Failed to open %s \n", filename);
719 xbt_dynar_t nodes = xbt_graph_get_nodes (span);
720 xbt_dynar_t edges = xbt_graph_get_edges (span);
723 fprintf (file, "%lu\n", xbt_dynar_length (nodes));
724 xbt_dynar_foreach (nodes, cpt, node) {
726 fprintf (file, "%s\n", nname(node));
728 fprintf (file, "%p\n", node);
731 fprintf (file, "%lu\n", xbt_dynar_length (edges));
733 xbt_dynar_foreach (edges, cpt, edge) {
734 xbt_node_t source = xbt_graph_edge_get_source (edge);
735 xbt_node_t target = xbt_graph_edge_get_target (edge);
738 fprintf (file, "%s %s %s\n", ename(edge), nname(source), nname(target));
740 fprintf (file, "%s %p %p\n", ename(edge), source, target);
744 fprintf (file, "%p %s %s\n", edge, nname(source), nname(target));
746 fprintf (file, "%p %p %p\n", edge, source, target);