3 /* a generic graph library. */
5 /* Copyright (c) 2006 Darina Dimitrova, Arnaud Legrand. */
6 /* All rights reserved. */
8 /* This program is free software; you can redistribute it and/or modify it
9 * under the terms of the license (GNU LGPL) which comes with this package. */
12 #include "xbt/sysdep.h"
14 #include "xbt/graph.h"
15 #include "graph_private.h"
16 #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 xbt_edge_t xbt_graph_get_edge(xbt_graph_t g, xbt_node_t src, xbt_node_t dst)
88 xbt_dynar_foreach(src->out, cursor, edge) {
89 DEBUG3("%p = %p--%p",edge,edge->src,edge->dst);
90 if((edge->src==src) && (edge->dst==dst)) return edge;
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)) return edge;
101 void *xbt_graph_node_get_data(xbt_node_t node)
106 void xbt_graph_node_set_data(xbt_node_t node, void *data)
111 void *xbt_graph_edge_get_data(xbt_edge_t edge)
116 void xbt_graph_edge_set_data(xbt_edge_t edge, void *data)
121 /** @brief Destructor
122 * @param g: poor victim
123 * @param node_free_function: function to use to free data associated to each node
124 * @param edge_free_function: function to use to free data associated to each edge
125 * @param graph_free_function: function to use to free data associated to g
127 * Free the graph structure.
129 void xbt_graph_free_graph(xbt_graph_t g,
130 void_f_pvoid_t node_free_function,
131 void_f_pvoid_t edge_free_function,
132 void_f_pvoid_t graph_free_function)
135 xbt_node_t node = NULL;
136 xbt_edge_t edge = NULL;
139 xbt_dynar_foreach(g->nodes, cursor, node) {
140 xbt_dynar_free(&(node->out));
141 xbt_dynar_free(&(node->in));
142 if (node_free_function)
143 (*node_free_function)(node->data);
146 xbt_dynar_foreach(g->edges, cursor, edge) {
147 if (edge_free_function)
148 (*edge_free_function)(edge->data);
151 xbt_dynar_foreach(g->nodes, cursor, node)
153 xbt_dynar_free(&(g->nodes));
155 xbt_dynar_foreach(g->edges, cursor, edge)
157 xbt_dynar_free(&(g->edges));
158 if(graph_free_function)
159 (*graph_free_function)(g->data);
166 /** @brief remove the given node from the given graph */
167 void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n,
168 void_f_pvoid_t node_free_function,
169 void_f_pvoid_t edge_free_function)
174 xbt_node_t node = NULL;
175 xbt_edge_t edge = NULL;
177 nbr = xbt_dynar_length(g->edges);
179 for (i = 0; i < nbr; i++) {
180 xbt_dynar_get_cpy(g->edges, cursor, &edge);
182 if ((edge->dst == n) || (edge->src == n)) {
183 xbt_graph_free_edge(g, edge, edge_free_function);
188 if ((node_free_function) && (n->data))
189 (*node_free_function)(n->data);
192 xbt_dynar_foreach(g->nodes, cursor, node)
194 xbt_dynar_cursor_rm(g->nodes, &cursor);
196 xbt_dynar_free(&(n->in));
197 xbt_dynar_free(&(n->out));
204 /** @brief remove the given edge from the given graph */
205 void xbt_graph_free_edge(xbt_graph_t g, xbt_edge_t e,
206 void_f_pvoid_t free_function)
210 xbt_edge_t edge = NULL;
212 if ((free_function) && (e->data))
213 (*free_function)(e->data);
215 xbt_dynar_foreach(g->edges, cursor, edge) {
218 idx = __xbt_find_in_dynar(edge->dst->in, edge);
219 xbt_dynar_remove_at(edge->dst->in, idx, NULL);
220 } else { /* only the out field is used */
221 idx = __xbt_find_in_dynar(edge->dst->out, edge);
222 xbt_dynar_remove_at(edge->dst->out, idx, NULL);
225 idx = __xbt_find_in_dynar(edge->src->out, edge);
226 xbt_dynar_remove_at(edge->src->out, idx, NULL);
228 xbt_dynar_cursor_rm(g->edges, &cursor);
235 int __xbt_find_in_dynar(xbt_dynar_t dynar, void *p)
241 xbt_dynar_foreach(dynar, cursor, tmp) {
248 /** @brief Retrieve the graph's nodes as a dynar */
249 xbt_dynar_t xbt_graph_get_nodes(xbt_graph_t g)
254 /** @brief Retrieve the graph's edges as a dynar */
255 xbt_dynar_t xbt_graph_get_edges(xbt_graph_t g)
260 /** @brief Retrieve the node at the source of the given edge */
261 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)
274 /** @brief Set the weight of the given edge */
275 void xbt_graph_edge_set_length(xbt_edge_t e, double length)
281 double xbt_graph_edge_get_length(xbt_edge_t e)
287 /** @brief construct the adjacency matrix corresponding to the given graph
289 * The weights are the distances between nodes
291 double *xbt_graph_get_length_matrix(xbt_graph_t g)
295 unsigned long idx, i;
297 xbt_edge_t edge = NULL;
298 xbt_node_t node = NULL;
301 # define D(u,v) d[(u)*n+(v)]
302 n = xbt_dynar_length(g->nodes);
304 d = (double *) xbt_new0(double, n * n);
306 for (i = 0; i < n * n; i++) {
310 xbt_dynar_foreach(g->nodes, cursor, node) {
312 D(cursor, cursor) = 0;
314 xbt_dynar_foreach(node->out, in_cursor, edge) {
315 if (edge->dst == node)
316 idx = __xbt_find_in_dynar(g->nodes, edge->src);
317 else /*case of undirected graphs */
318 idx = __xbt_find_in_dynar(g->nodes, edge->dst);
319 D(cursor, idx) = edge->length;
328 /** @brief Floyd-Warshall algorithm for shortest path finding
332 * The Floyd–Warshall algorithm takes as input an adjacency matrix
333 * representation of a weighted, directed graph (V, E). The weight of a
334 * path between two vertices is the sum of the weights of the edges along
335 * that path. The edges E of the graph may have negative weights, but the
336 * graph must not have any negative weight cycles. The algorithm computes,
337 * for each pair of vertices, the minimum weight among all paths between
338 * the two vertices. The running time complexity is Θ(|V|3).
340 void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d,
343 unsigned long i, j, k;
345 n = xbt_dynar_length(g->nodes);
347 # define D(u,v) d[(u)*n+(v)]
348 # define P(u,v) p[(u)*n+(v)]
350 for (i = 0; i < n * n; i++) {
355 for (i = 0; i < n; i++) {
356 for (j = 0; j < n; j++) {
358 P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i));
363 for (k = 0; k < n; k++) {
364 for (i = 0; i < n; i++) {
365 for (j = 0; j < n; j++) {
366 if ((D(i, k) != -1) && (D(k, j) != -1)) {
367 if ((D(i, j) == -1) || (D(i, j) > D(i, k) + D(k, j))) {
368 D(i, j) = D(i, k) + D(k, j);
382 /** @brief computes all-pairs shortest paths */
383 xbt_node_t *xbt_graph_shortest_paths(xbt_graph_t g)
387 unsigned long i, j, k;
393 # define P(u,v) p[(u)*n+(v)]
394 # define R(u,v) r[(u)*n+(v)]
396 n = xbt_dynar_length(g->nodes);
397 adj = xbt_graph_get_length_matrix(g);
398 d = xbt_new0(double, n * n);
399 p = xbt_new0(xbt_node_t, n * n);
400 r = xbt_new0(xbt_node_t, n * n);
402 xbt_floyd_algorithm(g, adj, d, p);
404 for (i = 0; i < n; i++) {
405 for (j = 0; j < n; j++) {
408 while ((P(i, k)) && (__xbt_find_in_dynar(g->nodes, P(i, k)) != i)) {
409 k = __xbt_find_in_dynar(g->nodes, P(i, k));
413 R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k));
426 /** @brief Extract a spanning tree of the given graph */
427 xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g)
430 int tree_size_max = xbt_dynar_length(g->nodes) - 1;
431 xbt_edge_t *tree = xbt_new0(xbt_edge_t, tree_size_max);
433 xbt_node_t node = NULL;
434 xbt_dynar_t edge_list = NULL;
435 xbt_heap_t heap = xbt_heap_new(10, NULL);
438 xbt_assert0(!(g->directed),
439 "Spanning trees do not make sense on directed graphs");
441 xbt_dynar_foreach(g->nodes, cursor, node) {
442 node->xbtdata = NULL;
445 node = xbt_dynar_getfirst_as(g->nodes, xbt_node_t);
446 node->xbtdata = (void *) 1;
447 edge_list = node->out;
448 xbt_dynar_foreach(edge_list, cursor, e)
449 xbt_heap_push(heap, e, -(e->length));
451 while ((edge = xbt_heap_pop(heap))) {
452 if ((edge->src->xbtdata) && (edge->dst->xbtdata))
454 tree[tree_size++] = edge;
455 if (!(edge->src->xbtdata)) {
456 edge->src->xbtdata = (void *) 1;
457 edge_list = edge->src->out;
458 xbt_dynar_foreach(edge_list, cursor, e) {
459 xbt_heap_push(heap, e, -(e->length));
462 edge->dst->xbtdata = (void *) 1;
463 edge_list = edge->dst->out;
464 xbt_dynar_foreach(edge_list, cursor, e) {
465 xbt_heap_push(heap, e, -(e->length));
468 if (tree_size == tree_size_max)
477 /** @brief Topological sort on the given graph
481 * In graph theory, a topological sort of a directed acyclic graph (DAG) is
482 * a linear ordering of its nodes which is compatible with the partial
483 * order R induced on the nodes where x comes before y (xRy) if there's a
484 * directed path from x to y in the DAG. An equivalent definition is that
485 * each node comes before all nodes to which it has edges. Every DAG has at
486 * least one topological sort, and may have many.
488 xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g)
496 n = xbt_dynar_length(g->nodes);
499 sorted = xbt_malloc(n * sizeof(xbt_node_t));
501 xbt_dynar_foreach(g->nodes, cursor, node)
502 node->xbtdata = xbt_new0(int, 1);
504 xbt_dynar_foreach(g->nodes, cursor, node)
505 xbt_graph_depth_visit(g, node, sorted, &idx);
507 xbt_dynar_foreach(g->nodes, cursor, node) {
509 node->xbtdata = NULL;
515 /** @brief First-depth graph traversal */
516 void xbt_graph_depth_visit(xbt_graph_t g, xbt_node_t n,
517 xbt_node_t * sorted, int *idx)
522 if (*((int *) (n->xbtdata)) == ALREADY_EXPLORED)
524 else if (*((int *) (n->xbtdata)) == CURRENTLY_EXPLORING)
525 THROW0(0, 0, "There is a cycle");
527 *((int *) (n->xbtdata)) = CURRENTLY_EXPLORING;
529 xbt_dynar_foreach(n->out, cursor, edge) {
530 xbt_graph_depth_visit(g, edge->dst, sorted, idx);
533 *((int *) (n->xbtdata)) = ALREADY_EXPLORED;
534 sorted[(*idx)--] = n;
538 /********************* Import and Export ******************/
539 static xbt_graph_t parsed_graph = NULL;
540 static xbt_dict_t parsed_nodes = NULL;
542 static void *(*__parse_node_label_and_data) (xbt_node_t, const char *,
543 const char *) = NULL;
544 static void *(*__parse_edge_label_and_data) (xbt_edge_t, const char *,
545 const char *) = NULL;
547 static void __parse_graph_begin(void)
550 if (A_graphxml_graph_isDirected == A_graphxml_graph_isDirected_true)
551 parsed_graph = xbt_graph_new_graph(1, NULL);
553 parsed_graph = xbt_graph_new_graph(0, NULL);
555 parsed_nodes = xbt_dict_new();
558 static void __parse_graph_end(void)
560 xbt_dict_free(&parsed_nodes);
564 static void __parse_node(void)
566 xbt_node_t node = xbt_graph_new_node(parsed_graph, NULL);
568 DEBUG1("<node name=\"%s\"/>", A_graphxml_node_name);
569 if (__parse_node_label_and_data)
570 node->data = __parse_node_label_and_data(node, A_graphxml_node_label,
571 A_graphxml_node_data);
572 xbt_graph_parse_get_double(&(node->position_x),
573 A_graphxml_node_position_x);
574 xbt_graph_parse_get_double(&(node->position_y),
575 A_graphxml_node_position_y);
577 xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL);
580 static void __parse_edge(void)
582 xbt_edge_t edge = xbt_graph_new_edge(parsed_graph,
583 xbt_dict_get(parsed_nodes,
584 A_graphxml_edge_source),
585 xbt_dict_get(parsed_nodes,
586 A_graphxml_edge_target),
589 if (__parse_edge_label_and_data)
590 edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label,
591 A_graphxml_edge_data);
593 xbt_graph_parse_get_double(&(edge->length), A_graphxml_edge_length);
595 DEBUG3("<edge source=\"%s\" target=\"%s\" length=\"%f\"/>",
596 (char *) (edge->src)->data,
597 (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge));
600 /** @brief Import a graph from a file following the GraphXML format */
601 xbt_graph_t xbt_graph_read(const char *filename,
602 void *(*node_label_and_data) (xbt_node_t,
605 void *(*edge_label_and_data) (xbt_edge_t,
610 xbt_graph_t graph = NULL;
612 __parse_node_label_and_data = node_label_and_data;
613 __parse_edge_label_and_data = edge_label_and_data;
615 xbt_graph_parse_reset_parser();
617 STag_graphxml_graph_fun = __parse_graph_begin;
618 ETag_graphxml_graph_fun = __parse_graph_end;
619 ETag_graphxml_node_fun = __parse_node;
620 ETag_graphxml_edge_fun = __parse_edge;
622 xbt_graph_parse_open(filename);
623 xbt_assert1((!(*xbt_graph_parse)()), "Parse error in %s", filename);
624 xbt_graph_parse_close();
626 graph = parsed_graph;
632 /** @brief Export the given graph in the GraphViz formatting for visualization */
633 void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename,
634 const char *(node_name) (xbt_node_t),
635 const char *(edge_name) (xbt_edge_t))
638 xbt_node_t node = NULL;
639 xbt_edge_t edge = NULL;
641 const char *name = NULL;
643 file = fopen(filename, "w");
644 xbt_assert1(file, "Failed to open %s \n", filename);
647 fprintf(file, "digraph test {\n");
649 fprintf(file, "graph test {\n");
651 fprintf(file, " graph [overlap=scale]\n");
653 fprintf(file, " node [shape=box, style=filled]\n");
655 " node [width=.3, height=.3, style=filled, color=skyblue]\n\n");
657 xbt_dynar_foreach(g->nodes, cursor, node) {
658 fprintf(file, " \"%p\" ", node);
659 if ((node_name) && ((name = node_name(node))))
660 fprintf(file, "[label=\"%s\"]", name);
661 fprintf(file, ";\n");
663 xbt_dynar_foreach(g->edges, cursor, edge) {
665 fprintf(file, " \"%p\" -> \"%p\"", edge->src, edge->dst);
667 fprintf(file, " \"%p\" -- \"%p\"", edge->src, edge->dst);
668 if ((edge_name) && ((name = edge_name(edge))))
669 fprintf(file, "[label=\"%s\"]", name);
670 fprintf(file, ";\n");
672 fprintf(file, "}\n");
676 /** @brief Export the given graph in the GraphXML format */
677 void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename,
678 const char *(node_name) (xbt_node_t),
679 const char *(edge_name) (xbt_edge_t),
680 const char *(node_data_print) (void *),
681 const char *(edge_data_print) (void *))
684 xbt_node_t node = NULL;
685 xbt_edge_t edge = NULL;
687 const char *name = NULL;
689 file = fopen(filename, "w");
690 xbt_assert1(file, "Failed to open %s \n", filename);
692 fprintf(file, "<?xml version='1.0'?>\n");
693 fprintf(file, "<!DOCTYPE graph SYSTEM \"graphxml.dtd\">\n");
695 fprintf(file, "<graph isDirected=\"true\">\n");
697 fprintf(file, "<graph isDirected=\"false\">\n");
698 xbt_dynar_foreach(g->nodes, cursor, node) {
699 fprintf(file, " <node name=\"%p\" ", node);
700 if ((node_name) && ((name = node_name(node))))
701 fprintf(file, "label=\"%s\" ", name);
702 if ((node_data_print) && ((name = node_data_print(node->data))))
703 fprintf(file, "data=\"%s\" ", name);
704 fprintf(file, ">\n");
706 xbt_dynar_foreach(g->edges, cursor, edge) {
707 fprintf(file, " <edge source=\"%p\" target =\"%p\" ",
708 edge->src, edge->dst);
709 if ((edge_name) && ((name = edge_name(edge))))
710 fprintf(file, "label=\"%s\" ", name);
711 if (edge->length >= 0.0)
712 fprintf(file, "length=\"%g\" ", edge->length);
713 if ((edge_data_print) && ((name = edge_data_print(edge->data))))
714 fprintf(file, "data=\"%s\" ", name);
715 fprintf(file, ">\n");
717 fprintf(file, "</graph>\n");