Cosmetics.
[mtp.git] / mtp_graph.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 #include "mtp_graph.h"
20
21 #include <iostream>
22 #include <float.h>
23 #include <stdlib.h>
24
25 using namespace std;
26
27 class Edge {
28 public:
29   int id, occupied;
30   scalar_t length, positivized_length;
31   Vertex *origin_vertex, *terminal_vertex;
32
33   // These are the links in the origin_vertex leaving edge list
34   Edge *next_leaving_edge, *pred_leaving_edge;
35
36   inline void revert();
37 };
38
39 class Vertex {
40 public:
41   int id;
42   Edge *leaving_edges;
43   scalar_t distance_from_source;
44   Edge *best_pred_edge_to_source;
45
46   int iteration; // Used in find_shortest_path to know if we already
47                  // added this vertex to the front
48   Vertex();
49   inline void add_edge(Edge *e);
50   inline void del_edge(Edge *e);
51 };
52
53 //////////////////////////////////////////////////////////////////////
54
55 void Edge::revert() {
56   length = - length;
57   positivized_length = 0;
58   origin_vertex->del_edge(this);
59   terminal_vertex->add_edge(this);
60   Vertex *t = terminal_vertex;
61   terminal_vertex = origin_vertex;
62   origin_vertex = t;
63 }
64
65 //////////////////////////////////////////////////////////////////////
66
67 Vertex::Vertex() {
68   leaving_edges = 0;
69 }
70
71 void Vertex::add_edge(Edge *e) {
72   e->next_leaving_edge = leaving_edges;
73   e->pred_leaving_edge = 0;
74   if(leaving_edges) { leaving_edges->pred_leaving_edge = e; }
75   leaving_edges = e;
76 }
77
78 void Vertex::del_edge(Edge *e) {
79   if(e == leaving_edges) { leaving_edges = e->next_leaving_edge; }
80   if(e->pred_leaving_edge) { e->pred_leaving_edge->next_leaving_edge = e->next_leaving_edge; }
81   if(e->next_leaving_edge) { e->next_leaving_edge->pred_leaving_edge = e->pred_leaving_edge; }
82 }
83
84 //////////////////////////////////////////////////////////////////////
85
86 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
87                    int *from, int *to,
88                    int source, int sink) {
89   _nb_vertices = nb_vertices;
90   _nb_edges = nb_edges;
91
92   _edges = new Edge[_nb_edges];
93   _vertices = new Vertex[_nb_vertices];
94   _front = new Vertex *[_nb_vertices];
95   _new_front = new Vertex *[_nb_vertices];
96
97   _source = &_vertices[source];
98   _sink = &_vertices[sink];
99
100   for(int v = 0; v < _nb_vertices; v++) {
101     _vertices[v].id = v;
102   }
103
104   for(int e = 0; e < nb_edges; e++) {
105     _vertices[from[e]].add_edge(_edges + e);
106     _edges[e].occupied = 0;
107     _edges[e].id = e;
108     _edges[e].origin_vertex = _vertices + from[e];
109     _edges[e].terminal_vertex = _vertices + to[e];
110   }
111
112   paths = 0;
113   nb_paths = 0;
114 }
115
116 MTPGraph::~MTPGraph() {
117   delete[] _vertices;
118   delete[] _edges;
119   delete[] _front;
120   delete[] _new_front;
121   for(int p = 0; p < nb_paths; p++) delete paths[p];
122   delete[] paths;
123 }
124
125 //////////////////////////////////////////////////////////////////////
126
127 void MTPGraph::print(ostream *os) {
128   for(int k = 0; k < _nb_edges; k++) {
129     Edge *e = _edges + k;
130     (*os) << e->origin_vertex->id
131          << " -> "
132          << e->terminal_vertex->id
133          << " "
134          << e->length;
135     if(e->occupied) {
136       (*os) << " *";
137     }
138     (*os) << endl;
139   }
140 }
141
142 void MTPGraph::print_dot(ostream *os) {
143   (*os) << "digraph {" << endl;
144   // (*os) << "        node [shape=circle];" << endl;
145   (*os) << "        " << _source->id << " [peripheries=2];" << endl;
146   (*os) << "        " << _sink->id << " [peripheries=2];" << endl;
147   for(int k = 0; k < _nb_edges; k++) {
148     Edge *e = _edges + k;
149     // (*os) << "  " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
150           // << ";"
151           // << endl;
152     if(e->occupied) {
153       (*os) << "        " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
154            << " [style=bold,color=black,label=\"" << e->length << "\"];" << endl;
155     } else {
156       (*os) << "        " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
157            << " [color=gray,label=\"" << e->length << "\"];" << endl;
158     }
159   }
160   (*os) << "}" << endl;
161 }
162
163 //////////////////////////////////////////////////////////////////////
164
165 void MTPGraph::initialize_positivized_lengths_with_min() {
166   scalar_t length_min = 0;
167   for(int n = 0; n < _nb_vertices; n++) {
168     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
169       length_min = min(e->length, length_min);
170     }
171   }
172   for(int n = 0; n < _nb_vertices; n++) {
173     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
174       e->positivized_length = e->length - length_min;
175     }
176   }
177 }
178
179 void MTPGraph::update_positivized_lengths() {
180   for(int k = 0; k < _nb_edges; k++) {
181     Edge *e = _edges + k;
182     e->positivized_length +=
183       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
184   }
185 }
186
187 void MTPGraph::force_positivized_lengths() {
188 #ifdef VERBOSE
189   scalar_t residual_error = 0.0;
190   scalar_t max_error = 0.0;
191 #endif
192   for(int n = 0; n < _nb_vertices; n++) {
193     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
194       if(e->positivized_length < 0) {
195 #ifdef VERBOSE
196         residual_error -= e->positivized_length;
197         max_error = max(max_error, fabs(e->positivized_length));
198 #endif
199         e->positivized_length = 0.0;
200       }
201     }
202   }
203 #ifdef VERBOSE
204   cerr << "residual_error " << residual_error << " max_error " << residual_error << endl;
205 #endif
206 }
207
208 // This method does not change the edge occupation. It update
209 // distance_from_source and best_pred_edge_to_source.
210 void MTPGraph::find_shortest_path(Vertex **_front, Vertex **_new_front) {
211   Vertex **tmp_front;
212   int tmp_front_size;
213   Vertex *v, *tv;
214   Edge *e;
215   scalar_t d;
216
217   for(int v = 0; v < _nb_vertices; v++) {
218     _vertices[v].distance_from_source = FLT_MAX;
219     _vertices[v].best_pred_edge_to_source = 0;
220     _vertices[v].iteration = 0;
221   }
222
223   int iteration = 0;
224
225   int _front_size = 0, _new_front_size;
226   _front[_front_size++] = _source;
227   _source->distance_from_source = 0;
228
229   do {
230     _new_front_size = 0;
231     iteration++;
232
233     for(int f = 0; f < _front_size; f++) {
234       v = _front[f];
235       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
236         d = v->distance_from_source + e->positivized_length;
237         tv = e->terminal_vertex;
238         if(d < tv->distance_from_source) {
239           tv->distance_from_source = d;
240           tv->best_pred_edge_to_source = e;
241           if(tv->iteration < iteration) {
242             _new_front[_new_front_size++] = tv;
243             tv->iteration = iteration;
244           }
245         }
246       }
247     }
248
249     tmp_front = _new_front;
250     _new_front = _front;
251     _front = tmp_front;
252
253     tmp_front_size = _new_front_size;
254     _new_front_size = _front_size;
255     _front_size = tmp_front_size;
256   } while(_front_size > 0);
257 }
258
259 void MTPGraph::find_best_paths(scalar_t *lengths) {
260   scalar_t total_length;
261   Vertex *v;
262   Edge *e;
263
264   for(int e = 0; e < _nb_edges; e++) {
265     _edges[e].length = lengths[e];
266     _edges[e].occupied = 0;
267     _edges[e].positivized_length = _edges[e].length;
268   }
269
270   // We use one iteration of find_shortest_path simply to propagate
271   // the distance to make all the edge lengths positive.
272   find_shortest_path(_front, _new_front);
273   update_positivized_lengths();
274
275   // #warning
276   // initialize_positivized_lengths_with_min();
277
278   do {
279     force_positivized_lengths();
280     find_shortest_path(_front, _new_front);
281     update_positivized_lengths();
282
283     total_length = 0.0;
284
285     // Do we reach the _sink?
286     if(_sink->best_pred_edge_to_source) {
287       // If yes, compute the length of the best path
288       v = _sink;
289       while(v->best_pred_edge_to_source) {
290         total_length += v->best_pred_edge_to_source->length;
291         v = v->best_pred_edge_to_source->origin_vertex;
292       }
293       // If that length is negative
294       if(total_length < 0.0) {
295 #ifdef VERBOSE
296         cerr << "Found a path of length " << total_length << endl;
297 #endif
298         // Invert all the edges along the best path
299         v = _sink;
300         while(v->best_pred_edge_to_source) {
301           e = v->best_pred_edge_to_source;
302           v = e->origin_vertex;
303           e->revert();
304           // This is the only place where we change the occupations of
305           // edges
306           e->occupied = 1 - e->occupied;
307         }
308       }
309     }
310
311   } while(total_length < 0.0);
312
313   for(int k = 0; k < _nb_edges; k++) {
314     Edge *e = _edges + k;
315     if(e->occupied) { e->revert(); }
316   }
317 }
318
319 int MTPGraph::retrieve_one_path(Edge *e, int *nodes) {
320   Edge *f, *next = 0;
321   int l = 0;
322
323   if(nodes) { nodes[l++] = e->origin_vertex->id; }
324   else l++;
325
326   while(e->terminal_vertex != _sink) {
327     if(nodes) { nodes[l++] = e->terminal_vertex->id; }
328     else l++;
329     int nb_choices = 0;
330     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
331       if(f->occupied) { nb_choices++; next = f; }
332       if(nb_choices == 0) {
333         cerr << "Non-sink path end point?!" << endl;
334         abort();
335       }
336       if(nb_choices > 1) {
337         cerr << "Non node-disjoint path, can not retrieve." << endl;
338         abort();
339       }
340     }
341     e = next;
342   }
343
344   if(nodes) { nodes[l++] = e->terminal_vertex->id; }
345   else l++;
346
347   return l;
348 }
349
350 void MTPGraph::retrieve_disjoint_paths() {
351   Edge *e;
352
353   for(int p = 0; p < nb_paths; p++) delete paths[p];
354   delete[] paths;
355
356   nb_paths = 0;
357   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
358     if(e->occupied) { nb_paths++; }
359   }
360
361   paths = new Path *[nb_paths];
362
363   int p = 0;
364   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
365     if(e->occupied) {
366       int l = retrieve_one_path(e, 0);
367       paths[p] = new Path(l);
368       retrieve_one_path(e, paths[p]->nodes);
369       p++;
370     }
371   }
372 }