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