Update.
[mtp.git] / mtp_graph.cc
1
2 /*
3  *  mtp is the ``Multi Tracked Paths'', an implementation of the
4  *  k-shortest paths algorithm for multi-target tracking.
5  *
6  *  Copyright (c) 2012 Idiap Research Institute, http://www.idiap.ch/
7  *  Written by Francois Fleuret <francois.fleuret@idiap.ch>
8  *
9  *  This file is part of mtp.
10  *
11  *  mtp is free software: you can redistribute it and/or modify it
12  *  under the terms of the GNU General Public License version 3 as
13  *  published by the Free Software Foundation.
14  *
15  *  mtp is distributed in the hope that it will be useful, but WITHOUT
16  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
18  *  License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with selector.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #include "mtp_graph.h"
26
27 #include <iostream>
28 #include <float.h>
29 #include <stdlib.h>
30
31 using namespace std;
32
33 class Edge {
34 public:
35   int id, occupied;
36   scalar_t length, positivized_length;
37   Vertex *origin_vertex, *terminal_vertex;
38
39   // These are the links in the origin_vertex leaving edge list
40   Edge *next_leaving_edge, *pred_leaving_edge;
41
42   inline void invert();
43 };
44
45 class Vertex {
46 public:
47   int id;
48   Edge *leaving_edges;
49   scalar_t distance_from_source;
50   Edge *pred_edge_toward_source;
51
52   int last_change; // Used to mark which edges have already been
53                    // processed in some methods
54
55   Vertex();
56
57   inline void add_leaving_edge(Edge *e);
58   inline void del_leaving_edge(Edge *e);
59 };
60
61 //////////////////////////////////////////////////////////////////////
62
63 void Edge::invert() {
64   length = - length;
65   positivized_length = - positivized_length;
66   origin_vertex->del_leaving_edge(this);
67   terminal_vertex->add_leaving_edge(this);
68   Vertex *t = terminal_vertex;
69   terminal_vertex = origin_vertex;
70   origin_vertex = t;
71 }
72
73 //////////////////////////////////////////////////////////////////////
74
75 Vertex::Vertex() {
76   leaving_edges = 0;
77 }
78
79 void Vertex::add_leaving_edge(Edge *e) {
80   e->next_leaving_edge = leaving_edges;
81   e->pred_leaving_edge = 0;
82   if(leaving_edges) { leaving_edges->pred_leaving_edge = e; }
83   leaving_edges = e;
84 }
85
86 void Vertex::del_leaving_edge(Edge *e) {
87   if(e == leaving_edges) {
88     leaving_edges = e->next_leaving_edge;
89   }
90   if(e->pred_leaving_edge) {
91     e->pred_leaving_edge->next_leaving_edge = e->next_leaving_edge;
92   }
93   if(e->next_leaving_edge) {
94     e->next_leaving_edge->pred_leaving_edge = e->pred_leaving_edge;
95   }
96 }
97
98 //////////////////////////////////////////////////////////////////////
99
100 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
101                    int *vertex_from, int *vertex_to,
102                    int source, int sink) {
103   _nb_vertices = nb_vertices;
104   _nb_edges = nb_edges;
105
106   _edges = new Edge[_nb_edges];
107   _vertices = new Vertex[_nb_vertices];
108   _front = new Vertex *[_nb_vertices];
109   _new_front = new Vertex *[_nb_vertices];
110
111   _source = &_vertices[source];
112   _sink = &_vertices[sink];
113
114   for(int k = 0; k < _nb_vertices; k++) {
115     _vertices[k].id = k;
116   }
117
118   for(int e = 0; e < nb_edges; e++) {
119     _vertices[vertex_from[e]].add_leaving_edge(_edges + e);
120     _edges[e].occupied = 0;
121     _edges[e].id = e;
122     _edges[e].origin_vertex = _vertices + vertex_from[e];
123     _edges[e].terminal_vertex = _vertices + vertex_to[e];
124   }
125
126   paths = 0;
127   nb_paths = 0;
128 }
129
130 MTPGraph::~MTPGraph() {
131   delete[] _vertices;
132   delete[] _edges;
133   delete[] _front;
134   delete[] _new_front;
135   for(int p = 0; p < nb_paths; p++) delete paths[p];
136   delete[] paths;
137 }
138
139 //////////////////////////////////////////////////////////////////////
140
141 void MTPGraph::print(ostream *os) {
142   for(int k = 0; k < _nb_edges; k++) {
143     Edge *e = _edges + k;
144     (*os) << e->origin_vertex->id
145          << " -> "
146          << e->terminal_vertex->id
147          << " "
148          << e->length;
149     if(e->occupied) {
150       (*os) << " *";
151     }
152     (*os) << endl;
153   }
154 }
155
156 void MTPGraph::print_dot(ostream *os) {
157   (*os) << "digraph {" << endl;
158   (*os) << "        rankdir=\"LR\";" << endl;
159   (*os) << "        node [shape=circle,width=0.75,fixedsize=true];" << endl;
160   (*os) << "        edge [color=gray,arrowhead=open]" << endl;
161   (*os) << "        " << _source->id << " [peripheries=2];" << endl;
162   (*os) << "        " << _sink->id << " [peripheries=2];" << endl;
163   for(int k = 0; k < _nb_edges; k++) {
164     Edge *e = _edges + k;
165     // (*os) << "  " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
166     // << ";"
167     // << endl;
168     (*os) << "        " << e->origin_vertex->id << " -> " << e->terminal_vertex->id
169           << " [";
170     if(e->occupied) {
171       (*os) << "style=bold,color=black,";
172     }
173     (*os) << "label=\"" << e->length << "\"];" << endl;
174   }
175   (*os) << "}" << endl;
176 }
177
178 //////////////////////////////////////////////////////////////////////
179
180 void MTPGraph::update_positivized_lengths() {
181   for(int k = 0; k < _nb_edges; k++) {
182     Edge *e = _edges + k;
183     e->positivized_length +=
184       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
185   }
186 }
187
188 void MTPGraph::force_positivized_lengths() {
189 #ifdef VERBOSE
190   scalar_t residual_error = 0.0;
191   scalar_t max_error = 0.0;
192 #endif
193   for(int n = 0; n < _nb_vertices; n++) {
194     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
195       if(e->positivized_length < 0) {
196 #ifdef VERBOSE
197         residual_error -= e->positivized_length;
198         max_error = max(max_error, - e->positivized_length);
199 #endif
200         e->positivized_length = 0.0;
201       }
202     }
203   }
204 #ifdef VERBOSE
205   cerr << "residual_error " << residual_error << " max_error " << residual_error << endl;
206 #endif
207 }
208
209 int MTPGraph::is_dag() {
210   Vertex *v;
211   Edge *e;
212
213   // We put everybody in the front
214   for(int k = 0; k < _nb_vertices; k++) {
215     _vertices[k].last_change = -1;
216     _front[k] = &_vertices[k];
217   }
218
219   int iteration = 0;
220   int front_size = _nb_vertices, pred_front_size;
221
222   do {
223     // We set the iteration field of all vertex with incoming edges to
224     // the current iteration value
225     for(int f = 0; f < front_size; f++) {
226       v = _front[f];
227       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
228         e->terminal_vertex->last_change = iteration;
229       }
230     }
231
232     pred_front_size = front_size;
233     front_size = 0;
234
235     // We remove all the vertices without incoming edge
236     for(int f = 0; f < pred_front_size; f++) {
237       v = _front[f];
238       if(v->last_change == iteration) {
239         _front[front_size++] = v;
240       }
241     }
242
243     iteration++;
244   } while(front_size < pred_front_size);
245
246   return front_size == 0;
247 }
248
249 // This method does not change the edge occupation. It only set
250 // properly for every vertex the fields distance_from_source and
251 // pred_edge_toward_source.
252
253 void MTPGraph::find_shortest_path() {
254   Vertex **tmp_front;
255   Vertex *v, *tv;
256   Edge *e;
257   scalar_t d;
258
259 #ifdef DEBUG
260   if(is_dag()) {
261     cout << "find_shortest_path: DAG -> ok" << endl;
262   } else {
263     for(int e = 0; e < _nb_edges; e++) {
264       if(_edges[e].positivized_length < 0)  abort();
265     }
266     cout << "find_shortest_path: All positivized_length are positive -> ok" << endl;
267   }
268 #endif
269
270   for(int k = 0; k < _nb_vertices; k++) {
271     _vertices[k].distance_from_source = FLT_MAX;
272     _vertices[k].pred_edge_toward_source = 0;
273     _vertices[k].last_change = -1;
274   }
275
276   int iteration = 0;
277
278   int front_size = 0, new_front_size;
279   _front[front_size++] = _source;
280   _source->distance_from_source = 0;
281
282   do {
283     new_front_size = 0;
284
285     for(int f = 0; f < front_size; f++) {
286       v = _front[f];
287       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
288         d = v->distance_from_source + e->positivized_length;
289         tv = e->terminal_vertex;
290         if(d < tv->distance_from_source) {
291           tv->distance_from_source = d;
292           tv->pred_edge_toward_source = e;
293           if(tv->last_change < iteration) {
294             _new_front[new_front_size++] = tv;
295             tv->last_change = iteration;
296           }
297         }
298       }
299     }
300
301     tmp_front = _new_front; _new_front = _front; _front = tmp_front;
302
303     front_size = new_front_size;
304
305     iteration++;
306   } while(front_size > 0);
307 }
308
309 void MTPGraph::find_best_paths(scalar_t *lengths) {
310   scalar_t total_length;
311   Vertex *v;
312   Edge *e;
313
314   for(int e = 0; e < _nb_edges; e++) {
315     _edges[e].length = lengths[e];
316     _edges[e].occupied = 0;
317     _edges[e].positivized_length = _edges[e].length;
318   }
319
320   // We call find_shortest_path here to set properly the distances to
321   // the source, so that we can make all the edge lengths positive at
322   // the first iteration.
323   find_shortest_path();
324
325   do {
326     update_positivized_lengths();
327     force_positivized_lengths();
328     find_shortest_path();
329
330     total_length = 0.0;
331
332     // Do we reach the sink?
333     if(_sink->pred_edge_toward_source) {
334       // If yes, compute the length of the best path according to the
335       // original edge lengths
336       v = _sink;
337       while(v->pred_edge_toward_source) {
338         total_length += v->pred_edge_toward_source->length;
339         v = v->pred_edge_toward_source->origin_vertex;
340       }
341       // If that length is negative
342       if(total_length < 0.0) {
343 #ifdef VERBOSE
344         cerr << "Found a path of length " << total_length << endl;
345 #endif
346         // Invert all the edges along the best path
347         v = _sink;
348         while(v->pred_edge_toward_source) {
349           e = v->pred_edge_toward_source;
350           v = e->origin_vertex;
351           e->invert();
352           // This is the only place where we change the occupations of
353           // edges
354           e->occupied = 1 - e->occupied;
355         }
356       }
357     }
358
359   } while(total_length < 0.0);
360
361   // Put back the graph in its original state (i.e. invert edges which
362   // have been inverted in the process)
363   for(int k = 0; k < _nb_edges; k++) {
364     Edge *e = _edges + k;
365     if(e->occupied) { e->invert(); }
366   }
367 }
368
369 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
370   Edge *f, *next = 0;
371   int l = 0;
372
373   if(path) {
374     path->nodes[l++] = e->origin_vertex->id;
375     path->length = e->length;
376   } else l++;
377
378   while(e->terminal_vertex != _sink) {
379     if(path) {
380       path->nodes[l++] = e->terminal_vertex->id;
381       path->length += e->length;
382     } else l++;
383     int nb_choices = 0;
384     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
385       if(f->occupied) { nb_choices++; next = f; }
386       if(nb_choices == 0) {
387         cerr << "retrieve_one_path: Non-sink end point." << endl;
388         abort();
389       }
390       if(nb_choices > 1) {
391         cerr << "retrieve_one_path: Non node-disjoint paths." << endl;
392         abort();
393       }
394     }
395     e = next;
396   }
397
398   if(path) {
399     path->nodes[l++] = e->terminal_vertex->id;
400     path->length += e->length;
401   } else l++;
402
403   return l;
404 }
405
406 void MTPGraph::retrieve_disjoint_paths() {
407   Edge *e;
408
409   for(int p = 0; p < nb_paths; p++) delete paths[p];
410   delete[] paths;
411
412   nb_paths = 0;
413   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
414     if(e->occupied) { nb_paths++; }
415   }
416
417   paths = new Path *[nb_paths];
418
419   int p = 0;
420   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
421     if(e->occupied) {
422       int l = retrieve_one_path(e, 0);
423       paths[p] = new Path(l);
424       retrieve_one_path(e, paths[p]);
425       p++;
426     }
427   }
428 }