Cosmetics.
[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 <cmath>
28 #include <float.h>
29
30 using namespace std;
31
32 class Edge {
33 public:
34   int occupied;
35   scalar_t length, positivized_length;
36   Vertex *origin_vertex, *terminal_vertex;
37
38   // These fields are used for the linked list of a vertex's leaving
39   // edge list. We have to do insertions / deletions.
40   Edge *next_leaving_edge, *pred_leaving_edge;
41
42   inline void invert();
43 };
44
45 class Vertex {
46 public:
47   scalar_t distance_from_source;
48   Edge *pred_edge_toward_source;
49
50   Edge *leaving_edge_list_root;
51   Vertex **heap_slot;
52
53   Vertex();
54
55   inline void add_leaving_edge(Edge *e);
56   inline void del_leaving_edge(Edge *e);
57   inline void decrease_distance_in_heap(Vertex **heap);
58   inline void increase_distance_in_heap(Vertex **heap, Vertex **heap_bottom);
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   swap(terminal_vertex, origin_vertex);
69 }
70
71 //////////////////////////////////////////////////////////////////////
72
73 Vertex::Vertex() {
74   leaving_edge_list_root = 0;
75 }
76
77 void Vertex::add_leaving_edge(Edge *e) {
78   e->next_leaving_edge = leaving_edge_list_root;
79   e->pred_leaving_edge = 0;
80   if(leaving_edge_list_root) {
81     leaving_edge_list_root->pred_leaving_edge = e;
82   }
83   leaving_edge_list_root = e;
84 }
85
86 void Vertex::del_leaving_edge(Edge *e) {
87   if(e == leaving_edge_list_root) {
88     leaving_edge_list_root = 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 void Vertex::decrease_distance_in_heap(Vertex **heap) {
99   Vertex **p, **h;
100   // There is some beauty in that
101   h = heap_slot;
102   while(h > heap &&
103         (p = heap + (h - heap + 1) / 2 - 1,
104          (*p)->distance_from_source > (*h)->distance_from_source)) {
105     swap(*p, *h);
106     swap((*p)->heap_slot, (*h)->heap_slot);
107     h = p;
108   }
109 }
110
111 void Vertex::increase_distance_in_heap(Vertex **heap, Vertex **heap_bottom) {
112   Vertex **c1, **c2, **h;
113   // omg, that's beautiful
114   h = heap_slot;
115   while(c1 = heap + 2 * (h - heap) + 1,
116         c1 < heap_bottom &&
117         (c2 = c1 + 1,
118          (*c1)->distance_from_source < (*h)->distance_from_source
119          ||
120          (c2 < heap_bottom && (*c2)->distance_from_source < (*h)->distance_from_source)
121          )) {
122     if(c2 < heap_bottom && (*c2)->distance_from_source <= (*c1)->distance_from_source) {
123       swap(*c2, *h);
124       swap((*c2)->heap_slot, (*h)->heap_slot);
125       h = c2;
126     } else {
127       swap(*c1, *h);
128       swap((*c1)->heap_slot, (*h)->heap_slot);
129       h = c1;
130     }
131   }
132 }
133
134 //////////////////////////////////////////////////////////////////////
135
136 static int compare_vertices_on_distance(const void *v1, const void *v2) {
137   scalar_t delta =
138     (*((Vertex **) v1))->distance_from_source -
139     (*((Vertex **) v2))->distance_from_source;
140   if(delta < 0) return -1;
141   else if(delta > 0) return 1;
142   else return 0;
143 }
144
145 //////////////////////////////////////////////////////////////////////
146
147 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
148                    int *vertex_from, int *vertex_to,
149                    int source, int sink) {
150   _nb_vertices = nb_vertices;
151   _nb_edges = nb_edges;
152
153   _edges = new Edge[_nb_edges];
154   _vertices = new Vertex[_nb_vertices];
155   _heap = new Vertex *[_nb_vertices];
156   _dp_order = new Vertex *[_nb_vertices];
157
158   _source = &_vertices[source];
159   _sink = &_vertices[sink];
160
161   for(int e = 0; e < nb_edges; e++) {
162     _vertices[vertex_from[e]].add_leaving_edge(_edges + e);
163     _edges[e].occupied = 0;
164     _edges[e].origin_vertex = _vertices + vertex_from[e];
165     _edges[e].terminal_vertex = _vertices + vertex_to[e];
166   }
167
168   for(int v = 0; v < _nb_vertices; v++) {
169     _heap[v] = &_vertices[v];
170     _vertices[v].heap_slot = &_heap[v];
171   }
172
173   paths = 0;
174   nb_paths = 0;
175
176   compute_dp_ranks();
177   for(int v = 0; v < _nb_vertices; v++) { _dp_order[v] = &_vertices[v]; }
178   qsort(_dp_order, _nb_vertices, sizeof(Vertex *), compare_vertices_on_distance);
179 }
180
181 MTPGraph::~MTPGraph() {
182   delete[] _vertices;
183   delete[] _dp_order;
184   delete[] _heap;
185   delete[] _edges;
186   for(int p = 0; p < nb_paths; p++) delete paths[p];
187   delete[] paths;
188 }
189
190 //////////////////////////////////////////////////////////////////////
191
192 void MTPGraph::compute_dp_ranks() {
193   Vertex *v;
194   Edge *e;
195   int tv;
196
197   // This procedure computes for each node the longest link from the
198   // source and abort if the graph is not a DAG. It works by removing
199   // successively nodes without predecessor: At the first iteration it
200   // removes the source, then the nodes with incoming edge only from
201   // the source, etc. If it can remove all the nodes that way, the
202   // graph is a DAG. If at some point it can not remove node anymore
203   // and there are some remaining nodes, the graph is not a DAG. The
204   // rank of a node is the iteration at which is it removed, and we
205   // set the distance_from_source fields to this value.
206
207   int *nb_predecessors = new int[_nb_vertices];
208   int *without_predecessor = new int[_nb_vertices];
209   int *new_without_predecessor = new int[_nb_vertices];
210   int nb_without_predecessor, new_nb_without_predecessor;
211
212   for(int k = 0; k < _nb_vertices; k++) {
213     nb_predecessors[k] = 0;
214   }
215
216   for(int k = 0; k < _nb_vertices; k++) {
217     v = _vertices + k;
218     for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
219       tv = int(e->terminal_vertex - _vertices);
220       nb_predecessors[tv]++;
221     }
222   }
223
224   nb_without_predecessor = 0;
225   for(int k = 0; k < _nb_vertices; k++) {
226     if(nb_predecessors[k] == 0) {
227       without_predecessor[nb_without_predecessor++] = k;
228     }
229   }
230
231   scalar_t rank = 1;
232   while(nb_without_predecessor > 0) {
233     new_nb_without_predecessor = 0;
234     for(int l = 0; l < nb_without_predecessor; l++) {
235       v = _vertices + without_predecessor[l];
236       v->distance_from_source = rank;
237       for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
238         tv = int(e->terminal_vertex - _vertices);
239         nb_predecessors[tv]--;
240         ASSERT(nb_predecessors[tv] >= 0);
241         if(nb_predecessors[tv] == 0) {
242           new_without_predecessor[new_nb_without_predecessor++] = tv;
243         }
244       }
245     }
246
247     swap(without_predecessor, new_without_predecessor);
248     nb_without_predecessor = new_nb_without_predecessor;
249     rank++;
250   }
251
252   for(int k = 0; k < _nb_vertices; k++) {
253     if(nb_predecessors[k] > 0) {
254       cerr << __FILE__ << ": The graph is not a DAG." << endl;
255       abort();
256     }
257   }
258
259   delete[] nb_predecessors;
260   delete[] without_predecessor;
261   delete[] new_without_predecessor;
262 }
263
264 //////////////////////////////////////////////////////////////////////
265
266 void MTPGraph::print(ostream *os) {
267   for(int k = 0; k < _nb_edges; k++) {
268     Edge *e = _edges + k;
269     (*os) << e->origin_vertex - _vertices
270           << " -> "
271           << e->terminal_vertex - _vertices
272           << " (" << e->length << ")";
273     if(e->occupied) { (*os) << " *"; }
274     (*os) << endl;
275   }
276 }
277
278 void MTPGraph::print_dot(ostream *os) {
279   (*os) << "digraph {" << endl;
280   (*os) << "        rankdir=\"LR\";" << endl;
281   (*os) << "        node [shape=circle,width=0.75,fixedsize=true];" << endl;
282   (*os) << "        edge [color=gray,arrowhead=open]" << endl;
283   (*os) << "        " << _source - _vertices << " [peripheries=2];" << endl;
284   (*os) << "        " << _sink - _vertices << " [peripheries=2];" << endl;
285   for(int k = 0; k < _nb_edges; k++) {
286     Edge *e = _edges + k;
287     (*os) << "        "
288           << e->origin_vertex - _vertices
289           << " -> "
290           << e->terminal_vertex - _vertices
291           << " [";
292     if(e->occupied) {
293       (*os) << "style=bold,color=black,";
294     }
295     (*os) << "label=\"" << e->length << "\"];" << endl;
296   }
297   (*os) << "}" << endl;
298 }
299
300 //////////////////////////////////////////////////////////////////////
301
302 void MTPGraph::update_positivized_lengths() {
303   for(int k = 0; k < _nb_edges; k++) {
304     Edge *e = _edges + k;
305     e->positivized_length +=
306       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
307   }
308 }
309
310 void MTPGraph::force_positivized_lengths() {
311 #ifdef VERBOSE
312   scalar_t residual_error = 0.0;
313   scalar_t max_error = 0.0;
314 #endif
315   for(int k = 0; k < _nb_edges; k++) {
316     Edge *e = _edges + k;
317
318     if(e->positivized_length < 0) {
319 #ifdef VERBOSE
320       residual_error -= e->positivized_length;
321       max_error = max(max_error, - e->positivized_length);
322 #endif
323       e->positivized_length = 0.0;
324     }
325   }
326 #ifdef VERBOSE
327   cerr << __FILE__ << ": residual_error " << residual_error << " max_error " << residual_error << endl;
328 #endif
329 }
330
331 void MTPGraph::dp_compute_distances() {
332   Vertex *v, *tv;
333   Edge *e;
334   scalar_t d;
335
336   for(int k = 0; k < _nb_vertices; k++) {
337     _vertices[k].distance_from_source = FLT_MAX;
338     _vertices[k].pred_edge_toward_source = 0;
339   }
340
341   _source->distance_from_source = 0;
342
343   for(int k = 0; k < _nb_vertices; k++) {
344     v = _dp_order[k];
345     for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
346       d = v->distance_from_source + e->positivized_length;
347       tv = e->terminal_vertex;
348       if(d < tv->distance_from_source) {
349         tv->distance_from_source = d;
350         tv->pred_edge_toward_source = e;
351       }
352     }
353   }
354 }
355
356 // This method does not change the edge occupation. It only sets
357 // properly, for every vertex, the fields distance_from_source and
358 // pred_edge_toward_source.
359
360 void MTPGraph::find_shortest_path() {
361   Vertex *v, *tv, **last_slot;
362   Edge *e;
363   scalar_t d;
364
365   for(int k = 0; k < _nb_vertices; k++) {
366     _vertices[k].distance_from_source = FLT_MAX;
367     _vertices[k].pred_edge_toward_source = 0;
368   }
369
370   _heap_size = _nb_vertices;
371   _source->distance_from_source = 0;
372   _source->decrease_distance_in_heap(_heap);
373
374   do {
375     // Get the closest to the source
376     v = _heap[0];
377
378     // Remove it from the heap (swap it with the last_slot in the heap, and
379     // update the distance of that one)
380     _heap_size--;
381     last_slot = _heap + _heap_size;
382     swap(*_heap, *last_slot); swap((*_heap)->heap_slot, (*last_slot)->heap_slot);
383     _heap[0]->increase_distance_in_heap(_heap, _heap + _heap_size);
384
385     // Now update the neighbors of the node currently closest to the
386     // source
387     for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
388       d = v->distance_from_source + e->positivized_length;
389       tv = e->terminal_vertex;
390       if(d < tv->distance_from_source) {
391         ASSERT(tv->heap_slot - _heap < _heap_size);
392         tv->distance_from_source = d;
393         tv->pred_edge_toward_source = e;
394         tv->decrease_distance_in_heap(_heap);
395       }
396     }
397   } while(_heap_size > 0);
398 }
399
400 void MTPGraph::find_best_paths(scalar_t *lengths) {
401   scalar_t shortest_path_length;
402   Vertex *v;
403   Edge *e;
404
405   for(int e = 0; e < _nb_edges; e++) {
406     _edges[e].length = lengths[e];
407     _edges[e].occupied = 0;
408     _edges[e].positivized_length = _edges[e].length;
409   }
410
411   // Compute the distance of all the nodes from the source by just
412   // visiting them in the proper DAG ordering we computed when
413   // building the graph
414   dp_compute_distances();
415
416   do {
417     // Use the current distance from the source to make all edge
418     // lengths positive
419     update_positivized_lengths();
420     // Fix numerical errors
421     force_positivized_lengths();
422
423     find_shortest_path();
424
425     shortest_path_length = 0.0;
426
427     // Do we reach the sink?
428     if(_sink->pred_edge_toward_source) {
429       // If yes, compute the length of the best path according to the
430       // original edge lengths
431       v = _sink;
432       while(v->pred_edge_toward_source) {
433         shortest_path_length += v->pred_edge_toward_source->length;
434         v = v->pred_edge_toward_source->origin_vertex;
435       }
436       // If that length is negative
437       if(shortest_path_length < 0.0) {
438 #ifdef VERBOSE
439         cerr << __FILE__ << ": Found a path of length " << shortest_path_length << endl;
440 #endif
441         // Invert all the edges along the best path
442         v = _sink;
443         while(v->pred_edge_toward_source) {
444           e = v->pred_edge_toward_source;
445           v = e->origin_vertex;
446           e->invert();
447           // This is the only place where we change the occupations of
448           // edges
449           e->occupied = 1 - e->occupied;
450         }
451       }
452     }
453
454   } while(shortest_path_length < 0.0);
455
456   // Put back the graph in its original state (i.e. invert edges which
457   // have been inverted in the process)
458   for(int k = 0; k < _nb_edges; k++) {
459     e = _edges + k;
460     if(e->occupied) { e->invert(); }
461   }
462 }
463
464 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
465   Edge *f, *next = 0;
466   int l = 0, nb_occupied_next;
467
468   if(path) {
469     path->nodes[l++] = int(e->origin_vertex - _vertices);
470     path->length = e->length;
471   } else l++;
472
473   while(e->terminal_vertex != _sink) {
474     if(path) {
475       path->nodes[l++] = int(e->terminal_vertex - _vertices);
476       path->length += e->length;
477     } else l++;
478
479     nb_occupied_next = 0;
480     for(f = e->terminal_vertex->leaving_edge_list_root; f; f = f->next_leaving_edge) {
481       if(f->occupied) { nb_occupied_next++; next = f; }
482     }
483
484 #ifdef DEBUG
485     if(nb_occupied_next == 0) {
486       cerr << __FILE__ << ": retrieve_one_path: Non-sink end point." << endl;
487       abort();
488     }
489
490     else if(nb_occupied_next > 1) {
491       cerr << __FILE__ << ": retrieve_one_path: Non node-disjoint paths." << endl;
492       abort();
493     }
494 #endif
495
496     e = next;
497   }
498
499   if(path) {
500     path->nodes[l++] = int(e->terminal_vertex - _vertices);
501     path->length += e->length;
502   } else l++;
503
504   return l;
505 }
506
507 void MTPGraph::retrieve_disjoint_paths() {
508   Edge *e;
509   int p, l;
510
511   for(int p = 0; p < nb_paths; p++) delete paths[p];
512   delete[] paths;
513
514   nb_paths = 0;
515   for(e = _source->leaving_edge_list_root; e; e = e->next_leaving_edge) {
516     if(e->occupied) { nb_paths++; }
517   }
518
519   paths = new Path *[nb_paths];
520
521   p = 0;
522   for(e = _source->leaving_edge_list_root; e; e = e->next_leaving_edge) {
523     if(e->occupied) {
524       l = retrieve_one_path(e, 0);
525       paths[p] = new Path(l);
526       retrieve_one_path(e, paths[p]);
527       p++;
528     }
529   }
530 }