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