Added README.md
[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   h = heap_slot;
101   while(1) {
102     if(h <= heap) break;
103     p = heap + ((h - heap + 1) >> 1) - 1;
104     if((*p)->distance_from_source <= distance_from_source) break;
105     swap((*p)->heap_slot, heap_slot);
106     swap(*p, *h);
107     h = p;
108   }
109 }
110
111 void Vertex::increase_distance_in_heap(Vertex **heap, Vertex **heap_bottom) {
112   Vertex **c1, **c2, **h;
113   h = heap_slot;
114   while(1) {
115     c1 = heap + 2 * (h - heap) + 1;
116     if(c1 >= heap_bottom) break;
117     c2 = c1 + 1;
118     if((*c1)->distance_from_source < distance_from_source) {
119       if(c2 < heap_bottom && (*c2)->distance_from_source < (*c1)->distance_from_source) {
120         swap((*c2)->heap_slot, heap_slot);
121         swap(*c2, *h);
122         h = c2;
123       } else {
124         swap((*c1)->heap_slot, heap_slot);
125         swap(*c1, *h);
126         h = c1;
127       }
128     } else {
129       if(c2 < heap_bottom && (*c2)->distance_from_source < distance_from_source) {
130         swap((*c2)->heap_slot, heap_slot);
131         swap(*c2, *h);
132         h = c2;
133       } else break;
134     }
135   }
136 }
137
138 //////////////////////////////////////////////////////////////////////
139
140 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
141                    int *vertex_from, int *vertex_to,
142                    int source, int sink) {
143   _nb_vertices = nb_vertices;
144   _nb_edges = nb_edges;
145
146   _edges = new Edge[_nb_edges];
147   _vertices = new Vertex[_nb_vertices];
148   _heap = new Vertex *[_nb_vertices];
149   _dp_order = new Vertex *[_nb_vertices];
150
151   _source = &_vertices[source];
152   _sink = &_vertices[sink];
153
154   for(int e = 0; e < nb_edges; e++) {
155     _vertices[vertex_from[e]].add_leaving_edge(&_edges[e]);
156     _edges[e].occupied = 0;
157     _edges[e].origin_vertex = &_vertices[vertex_from[e]];
158     _edges[e].terminal_vertex = &_vertices[vertex_to[e]];
159   }
160
161   for(int v = 0; v < _nb_vertices; v++) {
162     _heap[v] = &_vertices[v];
163     _vertices[v].heap_slot = &_heap[v];
164   }
165
166   paths = 0;
167   nb_paths = 0;
168
169   compute_dp_ordering();
170 }
171
172 MTPGraph::~MTPGraph() {
173   delete[] _vertices;
174   delete[] _dp_order;
175   delete[] _heap;
176   delete[] _edges;
177   for(int p = 0; p < nb_paths; p++) delete paths[p];
178   delete[] paths;
179 }
180
181 //////////////////////////////////////////////////////////////////////
182
183 void MTPGraph::print(ostream *os) {
184   for(int k = 0; k < _nb_edges; k++) {
185     Edge *e = &_edges[k];
186     (*os) << e->origin_vertex - _vertices
187           << " -> "
188           << e->terminal_vertex - _vertices
189           << " (" << e->length << ")";
190     if(e->occupied) { (*os) << " *"; }
191     (*os) << endl;
192   }
193 }
194
195 void MTPGraph::print_dot(ostream *os) {
196   (*os) << "digraph {" << endl;
197   (*os) << "        rankdir=\"LR\";" << endl;
198   (*os) << "        node [shape=circle,width=0.75,fixedsize=true];" << endl;
199   (*os) << "        edge [color=gray,arrowhead=open]" << endl;
200   (*os) << "        " << _source - _vertices << " [peripheries=2];" << endl;
201   (*os) << "        " << _sink - _vertices << " [peripheries=2];" << endl;
202   for(int k = 0; k < _nb_edges; k++) {
203     Edge *e = &_edges[k];
204     (*os) << "        "
205           << e->origin_vertex - _vertices
206           << " -> "
207           << e->terminal_vertex - _vertices
208           << " [";
209     if(e->occupied) {
210       (*os) << "style=bold,color=black,";
211     }
212     (*os) << "label=\"" << e->length << "\"];" << endl;
213   }
214   (*os) << "}" << endl;
215 }
216
217 //////////////////////////////////////////////////////////////////////
218
219 void MTPGraph::update_positivized_lengths() {
220   for(int k = 0; k < _nb_edges; k++) {
221     Edge *e = &_edges[k];
222     e->positivized_length +=
223       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
224   }
225 }
226
227 void MTPGraph::force_positivized_lengths() {
228 #ifdef VERBOSE
229   scalar_t residual_error = 0.0;
230   scalar_t max_error = 0.0;
231 #endif
232   for(int k = 0; k < _nb_edges; k++) {
233     Edge *e = &_edges[k];
234
235     if(e->positivized_length < 0) {
236 #ifdef VERBOSE
237       residual_error -= e->positivized_length;
238       max_error = max(max_error, - e->positivized_length);
239 #endif
240       e->positivized_length = 0.0;
241     }
242   }
243 #ifdef VERBOSE
244   cerr << __FILE__ << ": residual_error " << residual_error << " max_error " << max_error << endl;
245 #endif
246 }
247
248 void MTPGraph::dp_compute_distances() {
249   Vertex *v, *tv;
250   Edge *e;
251   scalar_t d;
252
253   for(int k = 0; k < _nb_vertices; k++) {
254     _vertices[k].distance_from_source = FLT_MAX;
255     _vertices[k].pred_edge_toward_source = 0;
256   }
257
258   _source->distance_from_source = 0;
259
260   for(int k = 0; k < _nb_vertices; k++) {
261     v = _dp_order[k];
262     for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
263       d = v->distance_from_source + e->positivized_length;
264       tv = e->terminal_vertex;
265       if(d < tv->distance_from_source) {
266         tv->distance_from_source = d;
267         tv->pred_edge_toward_source = e;
268       }
269     }
270   }
271 }
272
273 // This method does not change the edge occupation. It only sets
274 // properly, for every vertex, the fields distance_from_source and
275 // pred_edge_toward_source.
276
277 void MTPGraph::find_shortest_path() {
278   int heap_size;
279   Vertex *v, *tv, **last_slot;
280   Edge *e;
281   scalar_t d;
282
283   for(int k = 0; k < _nb_vertices; k++) {
284     _vertices[k].distance_from_source = FLT_MAX;
285     _vertices[k].pred_edge_toward_source = 0;
286   }
287
288   heap_size = _nb_vertices;
289   _source->distance_from_source = 0;
290   _source->decrease_distance_in_heap(_heap);
291
292   while(heap_size > 1) {
293     // Get the closest to the source
294     v = _heap[0];
295
296     // Remove it from the heap (swap it with the last_slot in the heap, and
297     // update the distance of that one)
298     heap_size--;
299     last_slot = _heap + heap_size;
300     swap(*_heap, *last_slot); swap((*_heap)->heap_slot, (*last_slot)->heap_slot);
301     (*_heap)->increase_distance_in_heap(_heap, last_slot);
302
303     // Now update the neighbors of the node currently closest to the
304     // source
305     for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
306       d = v->distance_from_source + e->positivized_length;
307       tv = e->terminal_vertex;
308       if(d < tv->distance_from_source) {
309         ASSERT(tv->heap_slot < last_slot);
310         tv->distance_from_source = d;
311         tv->pred_edge_toward_source = e;
312         tv->decrease_distance_in_heap(_heap);
313       }
314     }
315   }
316 }
317
318 void MTPGraph::find_best_paths(scalar_t *lengths) {
319   scalar_t shortest_path_length;
320   Vertex *v;
321   Edge *e;
322
323   for(int e = 0; e < _nb_edges; e++) {
324     _edges[e].length = lengths[e];
325     _edges[e].occupied = 0;
326     _edges[e].positivized_length = _edges[e].length;
327   }
328
329   // Compute the distance of all the nodes from the source by just
330   // visiting them in the proper DAG ordering we computed when
331   // building the graph
332   dp_compute_distances();
333
334   do {
335     // Use the current distance from the source to make all edge
336     // lengths positive
337     update_positivized_lengths();
338     // Fix numerical errors
339     force_positivized_lengths();
340
341     find_shortest_path();
342
343     shortest_path_length = 0.0;
344
345     // Do we reach the sink?
346     if(_sink->pred_edge_toward_source) {
347       // If yes, compute the length of the best path according to the
348       // original edge lengths
349       v = _sink;
350       while(v->pred_edge_toward_source) {
351         shortest_path_length += v->pred_edge_toward_source->length;
352         v = v->pred_edge_toward_source->origin_vertex;
353       }
354       // If that length is negative
355       if(shortest_path_length < 0.0) {
356 #ifdef VERBOSE
357         cerr << __FILE__ << ": Found a path of length " << shortest_path_length << endl;
358 #endif
359         // Invert all the edges along the best path
360         v = _sink;
361         while(v->pred_edge_toward_source) {
362           e = v->pred_edge_toward_source;
363           v = e->origin_vertex;
364           e->invert();
365           // This is the only place where we change the occupations of
366           // edges
367           e->occupied = 1 - e->occupied;
368         }
369       }
370     }
371
372   } while(shortest_path_length < 0.0);
373
374   // Put back the graph in its original state (i.e. invert edges which
375   // have been inverted in the process)
376   for(int k = 0; k < _nb_edges; k++) {
377     e = &_edges[k];
378     if(e->occupied) { e->invert(); }
379   }
380 }
381
382 int MTPGraph::retrieve_one_path(Edge *e, Path *path, int *used_edges) {
383   Edge *f, *next = 0;
384   int l = 0, nb_occupied_next;
385
386   if(path) {
387     path->nodes[l++] = int(e->origin_vertex - _vertices);
388     path->length = e->length;
389   } else l++;
390
391   while(e->terminal_vertex != _sink) {
392     if(path) {
393       path->nodes[l++] = int(e->terminal_vertex - _vertices);
394       path->length += e->length;
395     } else l++;
396
397     nb_occupied_next = 0;
398     for(f = e->terminal_vertex->leaving_edge_list_root; f; f = f->next_leaving_edge) {
399       if(f->occupied && !used_edges[f - _edges]) {
400         nb_occupied_next++; next = f;
401       }
402     }
403
404 #ifdef DEBUG
405     if(nb_occupied_next == 0) {
406       cerr << __FILE__ << ": retrieve_one_path: Non-sink end point." << endl;
407       abort();
408     }
409 #endif
410
411     if(path) { used_edges[next - _edges] = 1; }
412
413     e = next;
414   }
415
416   if(path) {
417     path->nodes[l++] = int(e->terminal_vertex - _vertices);
418     path->length += e->length;
419   } else l++;
420
421   return l;
422 }
423
424 //////////////////////////////////////////////////////////////////////
425
426 void MTPGraph::compute_dp_ordering() {
427   Vertex *v;
428   Edge *e;
429   int ntv;
430
431   // This method orders the nodes by putting first the ones with no
432   // predecessors, then going on adding nodes whose predecessors have
433   // all been already added. Computing the distances from the source
434   // by visiting nodes in that order is equivalent to DP.
435
436   int *nb_predecessors = new int[_nb_vertices];
437
438   Vertex **already_processed = _dp_order, **front = _dp_order, **new_front = _dp_order;
439
440   for(int k = 0; k < _nb_vertices; k++) {
441     nb_predecessors[k] = 0;
442   }
443
444   for(int k = 0; k < _nb_vertices; k++) {
445     v = &_vertices[k];
446     for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
447       ntv = int(e->terminal_vertex - _vertices);
448       nb_predecessors[ntv]++;
449     }
450   }
451
452   for(int k = 0; k < _nb_vertices; k++) {
453     if(nb_predecessors[k] == 0) {
454       *(front++) = _vertices + k;
455     }
456   }
457
458   while(already_processed < front) {
459     // Here, nodes before already_processed can be ignored, nodes
460     // before front were set to 0 predecessors during the previous
461     // iteration. During this new iteration, we have to visit the
462     // successors of these ones only, since they are the only ones
463     // which may end up with no predecessors.
464     new_front = front;
465     while(already_processed < front) {
466       v = *(already_processed++);
467       for(e = v->leaving_edge_list_root; e; e = e->next_leaving_edge) {
468         ntv = int(e->terminal_vertex - _vertices);
469         nb_predecessors[ntv]--;
470         ASSERT(nb_predecessors[ntv] >= 0);
471         if(nb_predecessors[ntv] == 0) {
472           *(new_front++) = e->terminal_vertex;
473         }
474       }
475     }
476     front = new_front;
477   }
478
479   if(already_processed < _dp_order + _nb_vertices) {
480     cerr << __FILE__ << ": The graph is not a DAG." << endl;
481     abort();
482   }
483
484   delete[] nb_predecessors;
485 }
486
487 //////////////////////////////////////////////////////////////////////
488
489 void MTPGraph::retrieve_disjoint_paths() {
490   Edge *e;
491   int p, l;
492   int *used_edges;
493
494   for(int p = 0; p < nb_paths; p++) delete paths[p];
495   delete[] paths;
496
497   nb_paths = 0;
498   for(e = _source->leaving_edge_list_root; e; e = e->next_leaving_edge) {
499     if(e->occupied) { nb_paths++; }
500   }
501
502   paths = new Path *[nb_paths];
503   used_edges = new int[_nb_edges];
504   for(int e = 0; e < _nb_edges; e++) {
505     used_edges[e] = 0;
506   }
507
508   p = 0;
509   for(e = _source->leaving_edge_list_root; e; e = e->next_leaving_edge) {
510     if(e->occupied && !used_edges[e - _edges]) {
511       l = retrieve_one_path(e, 0, used_edges);
512       paths[p] = new Path(l);
513       retrieve_one_path(e, paths[p], used_edges);
514       used_edges[e - _edges] = 1;
515       p++;
516     }
517   }
518
519   delete[] used_edges;
520 }