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. */
10 #include "xbt/sysdep.h"
12 #include "xbt/graph.h"
13 #include "graph_private.h"
14 #include "xbt/graphxml_parse.h"
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_graph, xbt, "Graph");
25 /** @brief Constructor
28 xbt_graph_t xbt_graph_new_graph(unsigned short int directed, void *data)
30 xbt_graph_t graph = NULL;
31 graph = xbt_new0(struct xbt_graph, 1);
32 graph->directed = directed;
34 graph->nodes = xbt_dynar_new(sizeof(xbt_node_t), NULL);
35 graph->edges = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
40 /** @brief add a node to the given graph */
41 xbt_node_t xbt_graph_new_node(xbt_graph_t g, void *data)
43 xbt_node_t node = NULL;
44 node = xbt_new0(struct xbt_node, 1);
47 /* only the "out" field is used */
48 node->in = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
50 node->out = xbt_dynar_new(sizeof(xbt_edge_t), NULL);
51 node->position_x = -1.0;
52 node->position_y = -1.0;
54 xbt_dynar_push(g->nodes, &node);
59 /** @brief add an edge to the given graph */
60 xbt_edge_t xbt_graph_new_edge(xbt_graph_t g,
61 xbt_node_t src, xbt_node_t dst, void *data)
63 xbt_edge_t edge = NULL;
65 edge = xbt_new0(struct xbt_edge, 1);
66 xbt_dynar_push(src->out, &edge);
68 xbt_dynar_push(dst->in, &edge);
69 else /* only the "out" field is used */
70 xbt_dynar_push(dst->out, &edge);
76 xbt_dynar_push(g->edges, &edge);
81 xbt_edge_t xbt_graph_get_edge(xbt_graph_t g, xbt_node_t src,
87 xbt_dynar_foreach(src->out, cursor, edge) {
88 DEBUG3("%p = %p--%p", edge, edge->src, edge->dst);
89 if ((edge->src == src) && (edge->dst == dst))
93 xbt_dynar_foreach(src->out, cursor, edge) {
94 DEBUG3("%p = %p--%p", edge, edge->src, edge->dst);
95 if ((edge->dst == src) && (edge->src == dst))
102 void *xbt_graph_node_get_data(xbt_node_t node)
107 void xbt_graph_node_set_data(xbt_node_t node, void *data)
112 void *xbt_graph_edge_get_data(xbt_edge_t edge)
117 void xbt_graph_edge_set_data(xbt_edge_t edge, void *data)
122 /** @brief Destructor
123 * @param g: poor victim
124 * @param node_free_function: function to use to free data associated to each node
125 * @param edge_free_function: function to use to free data associated to each edge
126 * @param graph_free_function: function to use to free data associated to g
128 * Free the graph structure.
130 void xbt_graph_free_graph(xbt_graph_t g,
131 void_f_pvoid_t node_free_function,
132 void_f_pvoid_t edge_free_function,
133 void_f_pvoid_t graph_free_function)
135 unsigned int cursor = 0;
136 xbt_node_t node = NULL;
137 xbt_edge_t edge = NULL;
140 xbt_dynar_foreach(g->nodes, cursor, node) {
141 xbt_dynar_free(&(node->out));
142 xbt_dynar_free(&(node->in));
143 if (node_free_function)
144 (*node_free_function) (node->data);
147 xbt_dynar_foreach(g->edges, cursor, edge) {
148 if (edge_free_function)
149 (*edge_free_function) (edge->data);
152 xbt_dynar_foreach(g->nodes, cursor, node)
154 xbt_dynar_free(&(g->nodes));
156 xbt_dynar_foreach(g->edges, cursor, edge)
158 xbt_dynar_free(&(g->edges));
159 if (graph_free_function)
160 (*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 double xbt_graph_edge_get_length(xbt_edge_t e)
292 /** @brief construct the adjacency matrix corresponding to the given graph
294 * The weights are the distances between nodes
296 double *xbt_graph_get_length_matrix(xbt_graph_t g)
298 unsigned int cursor = 0;
299 unsigned int in_cursor = 0;
300 unsigned long idx, i;
302 xbt_edge_t edge = NULL;
303 xbt_node_t node = NULL;
306 # define D(u,v) d[(u)*n+(v)]
307 n = xbt_dynar_length(g->nodes);
309 d = (double *) xbt_new0(double, n * n);
311 for (i = 0; i < n * n; i++) {
315 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_assert0(!(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 THROW0(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 /********************* Import and Export ******************/
545 static xbt_graph_t parsed_graph = NULL;
546 static xbt_dict_t parsed_nodes = NULL;
548 static void *(*__parse_node_label_and_data) (xbt_node_t, const char *,
549 const char *) = NULL;
550 static void *(*__parse_edge_label_and_data) (xbt_edge_t, const char *,
551 const char *) = NULL;
553 static void __parse_graph_begin(void)
556 if (A_graphxml_graph_isDirected == A_graphxml_graph_isDirected_true)
557 parsed_graph = xbt_graph_new_graph(1, NULL);
559 parsed_graph = xbt_graph_new_graph(0, NULL);
561 parsed_nodes = xbt_dict_new();
564 static void __parse_graph_end(void)
566 xbt_dict_free(&parsed_nodes);
570 static void __parse_node(void)
572 xbt_node_t node = xbt_graph_new_node(parsed_graph, NULL);
574 DEBUG1("<node name=\"%s\"/>", A_graphxml_node_name);
575 if (__parse_node_label_and_data)
576 node->data = __parse_node_label_and_data(node, A_graphxml_node_label,
577 A_graphxml_node_data);
578 xbt_graph_parse_get_double(&(node->position_x),
579 A_graphxml_node_position_x);
580 xbt_graph_parse_get_double(&(node->position_y),
581 A_graphxml_node_position_y);
583 xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
586 static void __parse_edge(void)
588 xbt_edge_t edge = xbt_graph_new_edge(parsed_graph,
589 xbt_dict_get(parsed_nodes,
590 A_graphxml_edge_source),
591 xbt_dict_get(parsed_nodes,
592 A_graphxml_edge_target),
595 if (__parse_edge_label_and_data)
596 edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label,
597 A_graphxml_edge_data);
599 xbt_graph_parse_get_double(&(edge->length), A_graphxml_edge_length);
601 DEBUG3("<edge source=\"%s\" target=\"%s\" length=\"%f\"/>",
602 (char *) (edge->src)->data,
603 (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge));
606 /** @brief Import a graph from a file following the GraphXML format */
607 xbt_graph_t xbt_graph_read(const char *filename,
608 void *(*node_label_and_data) (xbt_node_t,
611 void *(*edge_label_and_data) (xbt_edge_t,
616 xbt_graph_t graph = NULL;
618 __parse_node_label_and_data = node_label_and_data;
619 __parse_edge_label_and_data = edge_label_and_data;
621 xbt_graph_parse_reset_parser();
623 STag_graphxml_graph_fun = __parse_graph_begin;
624 ETag_graphxml_graph_fun = __parse_graph_end;
625 ETag_graphxml_node_fun = __parse_node;
626 ETag_graphxml_edge_fun = __parse_edge;
628 xbt_graph_parse_open(filename);
629 xbt_assert1((!(*xbt_graph_parse) ()), "Parse error in %s", filename);
630 xbt_graph_parse_close();
632 graph = parsed_graph;
638 /** @brief Export the given graph in the GraphViz formatting for visualization */
639 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
640 const char *(node_name) (xbt_node_t),
641 const char *(edge_name) (xbt_edge_t))
643 unsigned int cursor = 0;
644 xbt_node_t node = NULL;
645 xbt_edge_t edge = NULL;
647 const char *name = NULL;
649 file = fopen(filename, "w");
650 xbt_assert1(file, "Failed to open %s \n", filename);
653 fprintf(file, "digraph test {\n");
655 fprintf(file, "graph test {\n");
657 fprintf(file, " graph [overlap=scale]\n");
659 fprintf(file, " node [shape=box, style=filled]\n");
661 " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
663 xbt_dynar_foreach(g->nodes, cursor, node) {
664 fprintf(file, " \"%p\" ", node);
665 if ((node_name) && ((name = node_name(node))))
666 fprintf(file, "[label=\"%s\"]", name);
667 fprintf(file, ";\n");
669 xbt_dynar_foreach(g->edges, cursor, edge) {
671 fprintf(file, " \"%p\" -> \"%p\"", edge->src, edge->dst);
673 fprintf(file, " \"%p\" -- \"%p\"", edge->src, edge->dst);
674 if ((edge_name) && ((name = edge_name(edge))))
675 fprintf(file, "[label=\"%s\"]", name);
676 fprintf(file, ";\n");
678 fprintf(file, "}\n");
682 /** @brief Export the given graph in the GraphXML format */
683 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
684 const char *(node_name) (xbt_node_t),
685 const char *(edge_name) (xbt_edge_t),
686 const char *(node_data_print) (void *),
687 const char *(edge_data_print) (void *))
689 unsigned int cursor = 0;
690 xbt_node_t node = NULL;
691 xbt_edge_t edge = NULL;
693 const char *name = NULL;
695 file = fopen(filename, "w");
696 xbt_assert1(file, "Failed to open %s \n", filename);
698 fprintf(file, "<?xml version='1.0'?>\n");
699 fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
701 fprintf(file, "<graph isDirected=\"true\">\n");
703 fprintf(file, "<graph isDirected=\"false\">\n");
704 xbt_dynar_foreach(g->nodes, cursor, node) {
705 fprintf(file, " <node name=\"%p\" ", node);
706 if ((node_name) && ((name = node_name(node))))
707 fprintf(file, "label=\"%s\" ", name);
708 if ((node_data_print) && ((name = node_data_print(node->data))))
709 fprintf(file, "data=\"%s\" ", name);
710 fprintf(file, ">\n");
712 xbt_dynar_foreach(g->edges, cursor, edge) {
713 fprintf(file, " <edge source=\"%p\" target =\"%p\" ",
714 edge->src, edge->dst);
715 if ((edge_name) && ((name = edge_name(edge))))
716 fprintf(file, "label=\"%s\" ", name);
717 if (edge->length >= 0.0)
718 fprintf(file, "length=\"%g\" ", edge->length);
719 if ((edge_data_print) && ((name = edge_data_print(edge->data))))
720 fprintf(file, "data=\"%s\" ", name);
721 fprintf(file, ">\n");
723 fprintf(file, "</graph>\n");