Prevent the same vertex to be added twice to the front in find_shortest_path.
[mtp.git] / mtp.cc
1
2 ///////////////////////////////////////////////////////////////////////////
3 // This program is free software: you can redistribute it and/or modify  //
4 // it under the terms of the version 3 of the GNU General Public License //
5 // as published by the Free Software Foundation.                         //
6 //                                                                       //
7 // This program is distributed in the hope that it will be useful, but   //
8 // WITHOUT ANY WARRANTY; without even the implied warranty of            //
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      //
10 // General Public License for more details.                              //
11 //                                                                       //
12 // You should have received a copy of the GNU General Public License     //
13 // along with this program. If not, see <http://www.gnu.org/licenses/>.  //
14 //                                                                       //
15 // Written by and Copyright (C) Francois Fleuret                         //
16 // Contact <francois.fleuret@idiap.ch> for comments & bug reports        //
17 ///////////////////////////////////////////////////////////////////////////
18
19 // Multi-Tracked Path
20
21 // Takes the graph description file as input and produces a dot file.
22
23 // EXAMPLE: ./mtp ./graph2.txt  | dot -T pdf -o- | xpdf -
24
25 // #define VERBOSE
26
27 #include <iostream>
28 #include <fstream>
29 #include <cmath>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <float.h>
33
34 using namespace std;
35
36 typedef float scalar_t;
37
38 #ifdef DEBUG
39 #define ASSERT(x) if(!(x)) { \
40   std::cerr << "ASSERT FAILED IN " << __FILE__ << ":" << __LINE__ << endl; \
41   abort(); \
42 }
43 #else
44 #define ASSERT(x)
45 #endif
46
47 class Vertex;
48
49 class Edge {
50 public:
51   int id, occupied;
52   scalar_t length, work_length;
53   Vertex *terminal_vertex;
54   Edge *next, *pred;
55 };
56
57 class Vertex {
58 public:
59   int id, iteration;
60   Edge *root_edge;
61   scalar_t distance_from_source;
62   Vertex *pred_vertex;
63   Edge *pred_edge;
64
65   Vertex() { root_edge = 0; }
66
67   inline void add_edge(Edge *e) {
68     e->next = root_edge;
69     e->pred = 0;
70     if(root_edge) { root_edge->pred = e; }
71     root_edge = e;
72   }
73
74   inline void del_edge(Edge *e) {
75     if(e == root_edge) { root_edge = e->next; }
76     if(e->pred) { e->pred->next = e->next; }
77     if(e->next) { e->next->pred = e->pred; }
78   }
79 };
80
81 class Graph {
82   void initialize_work_lengths();
83   void update_work_length();
84   void find_shortest_path(Vertex **front, Vertex **new_front);
85
86   int nb_vertices;
87   Edge *edge_heap;
88   Vertex *vertices;
89   Vertex *source, *sink;
90 public:
91   Graph(int nb_vertices, int nb_edges, int *from, int *to, scalar_t *lengths,
92         int source, int sink);
93
94   ~Graph();
95
96   void find_best_paths(int *result_edge_occupation);
97   void print();
98 };
99
100 void Graph::print() {
101   for(int n = 0; n < nb_vertices; n++) {
102     for(Edge *e = vertices[n].root_edge; e; e = e->next) {
103       cout << n << " -> " << e->terminal_vertex->id << " " << e->length;
104       if(e->occupied) {
105         cout << " *";
106       }
107       cout << endl;
108     }
109   }
110 }
111
112 Graph::Graph(int nb_vrt, int nb_edges,
113              int *from, int *to, scalar_t *lengths,
114              int src, int snk) {
115   nb_vertices = nb_vrt;
116
117   edge_heap = new Edge[nb_edges];
118   vertices = new Vertex[nb_vertices];
119
120   source = &vertices[src];
121   sink = &vertices[snk];
122
123   for(int v = 0; v < nb_vertices; v++) {
124     vertices[v].id = v;
125   }
126
127   for(int e = 0; e < nb_edges; e++) {
128     vertices[from[e]].add_edge(&edge_heap[e]);
129     edge_heap[e].occupied = 0;
130     edge_heap[e].id = e;
131     edge_heap[e].length = lengths[e];
132     edge_heap[e].terminal_vertex = &vertices[to[e]];
133   }
134 }
135
136 Graph::~Graph() {
137   delete[] vertices;
138   delete[] edge_heap;
139 }
140
141 void Graph::initialize_work_lengths() {
142   scalar_t length_min = 0;
143   for(int n = 0; n < nb_vertices; n++) {
144     for(Edge *e = vertices[n].root_edge; e; e = e->next) {
145       length_min = min(e->length, length_min);
146     }
147   }
148   for(int n = 0; n < nb_vertices; n++) {
149     for(Edge *e = vertices[n].root_edge; e; e = e->next) {
150       e->work_length = e->length - length_min;
151     }
152   }
153 }
154
155 void Graph::update_work_length() {
156   for(int n = 0; n < nb_vertices; n++) {
157     scalar_t d = vertices[n].distance_from_source;
158     for(Edge *e = vertices[n].root_edge; e; e = e->next) {
159       e->work_length += d - e->terminal_vertex->distance_from_source;
160     }
161   }
162 }
163
164 void Graph::find_shortest_path(Vertex **front, Vertex **new_front) {
165   Vertex **tmp_front;
166   int tmp_front_size;
167   Vertex *v, *tv;
168   scalar_t d;
169
170 #ifdef DEBUG
171   for(int n = 0; n < nb_vertices; n++) {
172     for(Edge *e = vertices[n].root_edge; e; e = e->next) {
173       if(e->work_length < 0) {
174         cerr << "DEBUG error in find_shortest_path: Edge work lengths have to be positive."
175              << endl;
176         abort();
177       }
178     }
179   }
180 #endif
181
182   for(int v = 0; v < nb_vertices; v++) {
183     vertices[v].distance_from_source = FLT_MAX;
184     vertices[v].pred_vertex = 0;
185     vertices[v].pred_edge = 0;
186     vertices[v].iteration = 0;
187   }
188
189   int iteration = 0;
190
191   int front_size = 0, new_front_size;
192   front[front_size++] = source;
193   source->distance_from_source = 0;
194
195   do {
196     new_front_size = 0;
197     iteration++;
198     for(int f = 0; f < front_size; f++) {
199       v = front[f];
200       for(Edge *e = v->root_edge; e; e = e->next) {
201         d = v->distance_from_source + e->work_length;
202         tv = e->terminal_vertex;
203         if(d < tv->distance_from_source) {
204           tv->distance_from_source = d;
205           tv->pred_vertex = v;
206           tv->pred_edge = e;
207           if(tv->iteration < iteration) {
208             new_front[new_front_size++] = tv;
209             tv->iteration = iteration;
210           }
211         }
212       }
213     }
214
215     tmp_front = new_front;
216     new_front = front;
217     front = tmp_front;
218
219     tmp_front_size = new_front_size;
220     new_front_size = front_size;
221     front_size = tmp_front_size;
222   } while(front_size > 0);
223 }
224
225 void Graph::find_best_paths(int *result_edge_occupation) {
226   Vertex **front = new Vertex *[nb_vertices];
227   Vertex **new_front = new Vertex *[nb_vertices];
228
229   scalar_t total_length;
230
231   initialize_work_lengths();
232
233   do {
234     total_length = 0.0;
235     find_shortest_path(front, new_front);
236     update_work_length();
237
238     // Do we reach the sink?
239     if(sink->pred_edge) {
240
241       // If yes, compute the length of the best path
242       for(Vertex *v = sink; v->pred_edge; v = v->pred_vertex) {
243         total_length += v->pred_edge->length;
244       }
245
246       // If that length is negative
247       if(total_length < 0.0) {
248         // Invert all the edges along the best path
249         for(Vertex *v = sink; v->pred_edge; v = v->pred_vertex) {
250           Edge *e = v->pred_edge;
251           e->terminal_vertex = v->pred_vertex;
252           e->occupied = 1 - e->occupied;
253           e->length = - e->length;
254           e->work_length = - e->work_length;
255           v->pred_vertex->del_edge(e);
256           v->add_edge(e);
257         }
258       }
259     }
260   } while(total_length < 0.0);
261
262   delete[] front;
263   delete[] new_front;
264
265   for(int n = 0; n < nb_vertices; n++) {
266     Vertex *v = &vertices[n];
267     for(Edge *e = v->root_edge; e; e = e->next) {
268       result_edge_occupation[e->id] = e->occupied;
269     }
270   }
271 }
272
273 void find_best_paths(int nb_vertices,
274                      int nb_edges, int *ea, int *eb, scalar_t *el,
275                      int source, int sink,
276                      int *result_edge_occupation) {
277   Graph graph(nb_vertices, nb_edges, ea, eb, el, source, sink);
278   graph.find_best_paths(result_edge_occupation);
279 }
280
281 void dot_print(int nb_vertices,
282                int nb_edges, int *ea, int *eb, scalar_t *el,
283                int source, int sink,
284                int *edge_occupation) {
285   cout << "digraph {" << endl;
286   cout << "  node[shape=circle];" << endl;
287   for(int e = 0; e < nb_edges; e++) {
288     if(edge_occupation[e]) {
289       cout << "  " << ea[e] << " -> " << eb[e] << " [style=bold,color=black,label=\"" << el[e] << "\"];" << endl;
290     } else {
291       cout << "  " << ea[e] << " -> " << eb[e] << " [color=gray,label=\"" << el[e] << "\"];" << endl;
292     }
293   }
294   cout << "}" << endl;
295 }
296
297 //////////////////////////////////////////////////////////////////////
298
299 int main(int argc, char **argv) {
300
301   if(argc < 2) {
302     cerr << argv[0] << " <graph file>" << endl;
303     exit(EXIT_FAILURE);
304   }
305
306   ifstream *file = new ifstream(argv[1]);
307
308   int nb_edges, nb_vertices;
309   int source, sink;
310
311   if(file->good()) {
312
313     (*file) >> nb_vertices >> nb_edges;
314     (*file) >> source >> sink;
315
316     scalar_t *edge_lengths = new scalar_t[nb_edges];
317     int *vertex_from = new int[nb_edges];
318     int *vertex_to = new int[nb_edges];
319     int *result_edge_occupation = new int[nb_edges];
320
321     for(int e = 0; e < nb_edges; e++) {
322       (*file) >> vertex_from[e] >> vertex_to[e] >> edge_lengths[e];
323     }
324
325     find_best_paths(nb_vertices, nb_edges,
326                     vertex_from, vertex_to, edge_lengths,
327                     source, sink,
328                     result_edge_occupation);
329
330     dot_print(nb_vertices, nb_edges,
331               vertex_from, vertex_to, edge_lengths,
332               source, sink,
333               result_edge_occupation);
334
335     delete[] result_edge_occupation;
336     delete[] edge_lengths;
337     delete[] vertex_from;
338     delete[] vertex_to;
339
340   } else {
341
342     cerr << "Can not open " << argv[1] << endl;
343
344     delete file;
345     exit(EXIT_FAILURE);
346
347   }
348
349   delete file;
350   exit(EXIT_SUCCESS);
351 }