Update with the Dijkstra using a Binary Heap for the min-priority queue.
[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 occupied;
34   scalar_t length, positivized_length;
35   Vertex *origin_vertex, *terminal_vertex;
36
37   // These fields are used for the linked list of a vertex's leaving
38   // edge list. We have to do insertions / deletions.
39   Edge *next_leaving_edge, *pred_leaving_edge;
40
41   inline void invert();
42 };
43
44 class Vertex {
45 public:
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 **heap_position;
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 static int compare_vertex(const void *v1, const void *v2) {
101   return (*((Vertex **) v1))->last_change - (*((Vertex **) v2))->last_change;
102 }
103
104 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
105                    int *vertex_from, int *vertex_to,
106                    int source, int sink) {
107   _nb_vertices = nb_vertices;
108   _nb_edges = nb_edges;
109
110   _edges = new Edge[_nb_edges];
111   _vertices = new Vertex[_nb_vertices];
112   _heap = new Vertex *[_nb_vertices];
113   _dp_order = new Vertex *[_nb_vertices];
114
115   _source = &_vertices[source];
116   _sink = &_vertices[sink];
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].origin_vertex = _vertices + vertex_from[e];
122     _edges[e].terminal_vertex = _vertices + vertex_to[e];
123   }
124
125   for(int v = 0; v < _nb_vertices; v++) {
126     _heap[v] = &_vertices[v];
127     _vertices[v].heap_position = &_heap[v];
128   }
129
130   paths = 0;
131   nb_paths = 0;
132
133   if(check_DAG_and_set_last_change()) {
134     // Here the last_change field of every vertex tells us how many
135     // iterations of DP we need to reach it. Hence we only have to
136     // process the vertex in that order.
137     for(int v = 0; v < _nb_vertices; v++) { _dp_order[v] = &_vertices[v]; }
138     qsort(_dp_order, _nb_vertices, sizeof(Vertex *), compare_vertex);
139   } else {
140     cerr << __FILE__ << ": This graph is not a DAG." << endl;
141     abort();
142   }
143 }
144
145 MTPGraph::~MTPGraph() {
146   delete[] _vertices;
147   delete[] _dp_order;
148   delete[] _heap;
149   delete[] _edges;
150   for(int p = 0; p < nb_paths; p++) delete paths[p];
151   delete[] paths;
152 }
153
154 //////////////////////////////////////////////////////////////////////
155
156 void MTPGraph::print(ostream *os) {
157   for(int k = 0; k < _nb_edges; k++) {
158     Edge *e = _edges + k;
159     (*os) << e->origin_vertex - _vertices
160          << " -> "
161          << e->terminal_vertex - _vertices
162          << " "
163          << e->length;
164     if(e->occupied) {
165       (*os) << " *";
166     }
167     (*os) << endl;
168   }
169 }
170
171 void MTPGraph::print_dot(ostream *os) {
172   (*os) << "digraph {" << endl;
173   (*os) << "        rankdir=\"LR\";" << endl;
174   (*os) << "        node [shape=circle,width=0.75,fixedsize=true];" << endl;
175   (*os) << "        edge [color=gray,arrowhead=open]" << endl;
176   (*os) << "        " << _source - _vertices << " [peripheries=2];" << endl;
177   (*os) << "        " << _sink - _vertices << " [peripheries=2];" << endl;
178   for(int k = 0; k < _nb_edges; k++) {
179     Edge *e = _edges + k;
180     (*os) << "        "
181           << e->origin_vertex - _vertices
182           << " -> "
183           << e->terminal_vertex - _vertices
184           << " [";
185     if(e->occupied) {
186       (*os) << "style=bold,color=black,";
187     }
188     (*os) << "label=\"" << e->length << "\"];" << endl;
189   }
190   (*os) << "}" << endl;
191 }
192
193 //////////////////////////////////////////////////////////////////////
194
195 void MTPGraph::update_positivized_lengths() {
196   for(int k = 0; k < _nb_edges; k++) {
197     Edge *e = _edges + k;
198     e->positivized_length +=
199       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
200   }
201 }
202
203 void MTPGraph::force_positivized_lengths() {
204 #ifdef VERBOSE
205   scalar_t residual_error = 0.0;
206   scalar_t max_error = 0.0;
207 #endif
208   for(int k = 0; k < _nb_edges; k++) {
209     Edge *e = _edges + k;
210
211     if(e->positivized_length < 0) {
212
213 #ifdef VERBOSE
214       if((e->origin_vertex->last_change < 0 && e->terminal_vertex->last_change >= 0) ||
215          (e->origin_vertex->last_change >= 0 && e->terminal_vertex->last_change < 0)) {
216         cout << "Inconsistent non-connexity (this should never happen)." << endl;
217         abort();
218       }
219       if(e->origin_vertex->last_change >= 0 &&
220          e->terminal_vertex->last_change >= 0 &&
221          e->positivized_length < 0) {
222         residual_error -= e->positivized_length;
223         max_error = max(max_error, - e->positivized_length);
224       }
225 #endif
226       e->positivized_length = 0.0;
227     }
228   }
229 #ifdef VERBOSE
230   cerr << "residual_error " << residual_error << " max_error " << residual_error << endl;
231 #endif
232 }
233
234 int MTPGraph::check_DAG_and_set_last_change() {
235   Vertex *v;
236   Edge *e;
237
238   Vertex **active = new Vertex *[_nb_vertices];
239
240   // We put everybody in the active
241   for(int k = 0; k < _nb_vertices; k++) {
242     _vertices[k].last_change = 0;
243     active[k] = &_vertices[k];
244   }
245
246   int iteration = 1;
247   int nb_active = _nb_vertices, pred_nb_active;
248
249   do {
250     // We set the last_change field of all the vertices with incoming
251     // edges to the current iteration value
252     for(int f = 0; f < nb_active; f++) {
253       v = active[f];
254       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
255         e->terminal_vertex->last_change = iteration;
256       }
257     }
258
259     pred_nb_active = nb_active;
260     nb_active = 0;
261
262     // We keep all the vertices with incoming nodes
263     for(int f = 0; f < pred_nb_active; f++) {
264       v = active[f];
265       if(v->last_change == iteration) {
266         active[nb_active++] = v;
267       }
268     }
269
270     iteration++;
271   } while(nb_active < pred_nb_active);
272
273   delete[] active;
274
275   return nb_active == 0;
276 }
277
278 void MTPGraph::decrease_distance_in_heap(Vertex *v) {
279   Vertex **p, **h;
280   // There is some beauty in that
281   h = v->heap_position;
282   while(h > _heap &&
283         (p = _heap + (h - _heap + 1) / 2 - 1,
284          (*p)->distance_from_source > (*h)->distance_from_source)) {
285     swap(*p, *h);
286     swap((*p)->heap_position, (*h)->heap_position);
287     h = p;
288   }
289 }
290
291 void MTPGraph::increase_distance_in_heap(Vertex *v) {
292   Vertex **c1, **c2, **h;
293   // There is some beauty in that
294   h = v->heap_position;
295   while(c1 = _heap + 2 * (h - _heap + 1) - 1, c2 = c1 + 1,
296         (c1 < _heap + _heap_size &&
297          (*c1)->distance_from_source < (*h)->distance_from_source)
298         ||
299         (c2 < _heap + _heap_size &&
300           (*c2)->distance_from_source < (*h)->distance_from_source)
301         ) {
302     if(c1 < _heap + _heap_size &&
303        !(c2 < _heap + _heap_size &&
304          (*c2)->distance_from_source < (*c1)->distance_from_source)){
305       swap(*c1, *h);
306       swap((*c1)->heap_position, (*h)->heap_position);
307       h = c1;
308     } else {
309       swap(*c2, *h);
310       swap((*c2)->heap_position, (*h)->heap_position);
311       h = c2;
312     }
313   }
314 }
315
316 void MTPGraph::dp_distance_propagation() {
317   Vertex *v, *tv;
318   Edge *e;
319   scalar_t d;
320
321   for(int k = 0; k < _nb_vertices; k++) {
322     _vertices[k].distance_from_source = FLT_MAX;
323     _vertices[k].pred_edge_toward_source = 0;
324   }
325
326   _source->distance_from_source = 0;
327
328   for(int k = 0; k < _nb_vertices; k++) {
329     v = _dp_order[k];
330     for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
331       d = v->distance_from_source + e->positivized_length;
332       tv = e->terminal_vertex;
333       if(d < tv->distance_from_source) {
334         tv->distance_from_source = d;
335         tv->pred_edge_toward_source = e;
336         decrease_distance_in_heap(tv);
337       }
338     }
339   }
340 }
341
342 // This method does not change the edge occupation. It only sets
343 // properly, for every vertex, the fields distance_from_source and
344 // pred_edge_toward_source.
345
346 void MTPGraph::find_shortest_path() {
347   Vertex *v, *tv, **a, **b;
348   Edge *e;
349   scalar_t d;
350
351   for(int k = 0; k < _nb_vertices; k++) {
352     _vertices[k].distance_from_source = FLT_MAX;
353     _vertices[k].pred_edge_toward_source = 0;
354   }
355
356   _heap_size = _nb_vertices;
357   _source->distance_from_source = 0;
358   decrease_distance_in_heap(_source);
359
360   do {
361     // Get the closest to the source
362     v = _heap[0];
363
364     // Remove it from the heap (swap it with the last in the heap, and
365     // update the distance of that one)
366     _heap_size--;
367     a = _heap;
368     b = _heap + _heap_size;
369     swap(*a, *b); swap((*a)->heap_position, (*b)->heap_position);
370     increase_distance_in_heap(_heap[0]);
371
372     // Now update the neighbors of the currently closest to the source
373     for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
374       d = v->distance_from_source + e->positivized_length;
375       tv = e->terminal_vertex;
376       if(d < tv->distance_from_source) {
377         ASSERT(tv->heap_position - _heap < _heap_size);
378         tv->distance_from_source = d;
379         tv->pred_edge_toward_source = e;
380         decrease_distance_in_heap(tv);
381       }
382     }
383   } while(_heap_size > 0);
384 }
385
386 void MTPGraph::find_best_paths(scalar_t *lengths) {
387   scalar_t total_length;
388   Vertex *v;
389   Edge *e;
390
391   for(int e = 0; e < _nb_edges; e++) {
392     _edges[e].length = lengths[e];
393     _edges[e].occupied = 0;
394     _edges[e].positivized_length = _edges[e].length;
395   }
396
397   // Update the distance to the source in "good order"
398
399   dp_distance_propagation();
400
401   do {
402     update_positivized_lengths();
403     force_positivized_lengths();
404     find_shortest_path();
405
406     total_length = 0.0;
407
408     // Do we reach the sink?
409     if(_sink->pred_edge_toward_source) {
410       // If yes, compute the length of the best path according to the
411       // original edge lengths
412       v = _sink;
413       while(v->pred_edge_toward_source) {
414         total_length += v->pred_edge_toward_source->length;
415         v = v->pred_edge_toward_source->origin_vertex;
416       }
417       // If that length is negative
418       if(total_length < 0.0) {
419 #ifdef VERBOSE
420         cerr << "Found a path of length " << total_length << endl;
421 #endif
422         // Invert all the edges along the best path
423         v = _sink;
424         while(v->pred_edge_toward_source) {
425           e = v->pred_edge_toward_source;
426           v = e->origin_vertex;
427           e->invert();
428           // This is the only place where we change the occupations of
429           // edges
430           e->occupied = 1 - e->occupied;
431         }
432       }
433     }
434
435   } while(total_length < 0.0);
436
437   // Put back the graph in its original state (i.e. invert edges which
438   // have been inverted in the process)
439   for(int k = 0; k < _nb_edges; k++) {
440     e = _edges + k;
441     if(e->occupied) { e->invert(); }
442   }
443 }
444
445 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
446   Edge *f, *next = 0;
447   int l = 0, nb_occupied_next;
448
449   if(path) {
450     path->nodes[l++] = e->origin_vertex - _vertices;
451     path->length = e->length;
452   } else l++;
453
454   while(e->terminal_vertex != _sink) {
455     if(path) {
456       path->nodes[l++] = e->terminal_vertex - _vertices;
457       path->length += e->length;
458     } else l++;
459
460     nb_occupied_next = 0;
461     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
462       if(f->occupied) { nb_occupied_next++; next = f; }
463     }
464
465 #ifdef DEBUG
466     if(nb_occupied_next == 0) {
467       cerr << "retrieve_one_path: Non-sink end point." << endl;
468       abort();
469     }
470
471     else if(nb_occupied_next > 1) {
472       cerr << "retrieve_one_path: Non node-disjoint paths." << endl;
473       abort();
474     }
475 #endif
476
477     e = next;
478   }
479
480   if(path) {
481     path->nodes[l++] = e->terminal_vertex - _vertices;
482     path->length += e->length;
483   } else l++;
484
485   return l;
486 }
487
488 void MTPGraph::retrieve_disjoint_paths() {
489   Edge *e;
490   int p, l;
491
492   for(int p = 0; p < nb_paths; p++) delete paths[p];
493   delete[] paths;
494
495   nb_paths = 0;
496   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
497     if(e->occupied) { nb_paths++; }
498   }
499
500   paths = new Path *[nb_paths];
501
502   p = 0;
503   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
504     if(e->occupied) {
505       l = retrieve_one_path(e, 0);
506       paths[p] = new Path(l);
507       retrieve_one_path(e, paths[p]);
508       p++;
509     }
510   }
511 }