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