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