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