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