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   Vertex **active = new Vertex *[_nb_vertices];
231
232   // We put everybody in the active
233   for(int k = 0; k < _nb_vertices; k++) {
234     _vertices[k].distance_from_source = 0;
235     active[k] = &_vertices[k];
236   }
237
238   int iteration = 1;
239   int nb_active = _nb_vertices, pred_nb_active;
240
241   do {
242     // We set the distance_from_source field of all the vertices with incoming
243     // edges to the current iteration value
244     for(int f = 0; f < nb_active; f++) {
245       v = active[f];
246       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
247         e->terminal_vertex->distance_from_source = iteration;
248       }
249     }
250
251     pred_nb_active = nb_active;
252     nb_active = 0;
253
254     // We keep all the vertices with incoming nodes
255     for(int f = 0; f < pred_nb_active; f++) {
256       v = active[f];
257       if(v->distance_from_source == iteration) {
258         active[nb_active++] = v;
259       }
260     }
261
262     iteration++;
263   } while(nb_active < pred_nb_active);
264
265   delete[] active;
266
267   return nb_active == 0;
268 }
269
270 void MTPGraph::decrease_distance_in_heap(Vertex *v) {
271   Vertex **p, **h;
272   // There is some beauty in that
273   h = v->heap_slot;
274   while(h > _heap &&
275         (p = _heap + (h - _heap + 1) / 2 - 1,
276          (*p)->distance_from_source > (*h)->distance_from_source)) {
277     swap(*p, *h);
278     swap((*p)->heap_slot, (*h)->heap_slot);
279     h = p;
280   }
281 }
282
283 void MTPGraph::increase_distance_in_heap(Vertex *v) {
284   Vertex **c1, **c2, **h;
285   // There is some beauty in that
286   h = v->heap_slot;
287   while(c1 = _heap + 2 * (h - _heap + 1) - 1, c2 = c1 + 1,
288         (c1 < _heap + _heap_size && (*c1)->distance_from_source < (*h)->distance_from_source)
289         ||
290         (c2 < _heap + _heap_size && (*c2)->distance_from_source < (*h)->distance_from_source)
291         ) {
292     if(c1 < _heap + _heap_size &&
293      !(c2 < _heap + _heap_size && (*c2)->distance_from_source < (*c1)->distance_from_source)){
294       swap(*c1, *h);
295       swap((*c1)->heap_slot, (*h)->heap_slot);
296       h = c1;
297     } else {
298       swap(*c2, *h);
299       swap((*c2)->heap_slot, (*h)->heap_slot);
300       h = c2;
301     }
302   }
303 }
304
305 void MTPGraph::dp_distance_propagation() {
306   Vertex *v, *tv;
307   Edge *e;
308   scalar_t d;
309
310   for(int k = 0; k < _nb_vertices; k++) {
311     _vertices[k].distance_from_source = FLT_MAX;
312     _vertices[k].pred_edge_toward_source = 0;
313   }
314
315   _source->distance_from_source = 0;
316
317   for(int k = 0; k < _nb_vertices; k++) {
318     v = _dp_order[k];
319     for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
320       d = v->distance_from_source + e->positivized_length;
321       tv = e->terminal_vertex;
322       if(d < tv->distance_from_source) {
323         tv->distance_from_source = d;
324         tv->pred_edge_toward_source = e;
325         decrease_distance_in_heap(tv);
326       }
327     }
328   }
329 }
330
331 // This method does not change the edge occupation. It only sets
332 // properly, for every vertex, the fields distance_from_source and
333 // pred_edge_toward_source.
334
335 void MTPGraph::find_shortest_path() {
336   Vertex *v, *tv, **a, **b;
337   Edge *e;
338   scalar_t d;
339
340   for(int k = 0; k < _nb_vertices; k++) {
341     _vertices[k].distance_from_source = FLT_MAX;
342     _vertices[k].pred_edge_toward_source = 0;
343   }
344
345   _heap_size = _nb_vertices;
346   _source->distance_from_source = 0;
347   decrease_distance_in_heap(_source);
348
349   do {
350     // Get the closest to the source
351     v = _heap[0];
352
353     // Remove it from the heap (swap it with the last in the heap, and
354     // update the distance of that one)
355     _heap_size--;
356     a = _heap;
357     b = _heap + _heap_size;
358     swap(*a, *b); swap((*a)->heap_slot, (*b)->heap_slot);
359     increase_distance_in_heap(_heap[0]);
360
361     // Now update the neighbors of the currently closest to the source
362     for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
363       d = v->distance_from_source + e->positivized_length;
364       tv = e->terminal_vertex;
365       if(d < tv->distance_from_source) {
366         ASSERT(tv->heap_slot - _heap < _heap_size);
367         tv->distance_from_source = d;
368         tv->pred_edge_toward_source = e;
369         decrease_distance_in_heap(tv);
370       }
371     }
372   } while(_heap_size > 0);
373 }
374
375 void MTPGraph::find_best_paths(scalar_t *lengths) {
376   scalar_t total_length;
377   Vertex *v;
378   Edge *e;
379
380   for(int e = 0; e < _nb_edges; e++) {
381     _edges[e].length = lengths[e];
382     _edges[e].occupied = 0;
383     _edges[e].positivized_length = _edges[e].length;
384   }
385
386   // Update the distance to the source in "good order"
387
388   dp_distance_propagation();
389
390   do {
391     update_positivized_lengths();
392     force_positivized_lengths();
393     find_shortest_path();
394
395     total_length = 0.0;
396
397     // Do we reach the sink?
398     if(_sink->pred_edge_toward_source) {
399       // If yes, compute the length of the best path according to the
400       // original edge lengths
401       v = _sink;
402       while(v->pred_edge_toward_source) {
403         total_length += v->pred_edge_toward_source->length;
404         v = v->pred_edge_toward_source->origin_vertex;
405       }
406       // If that length is negative
407       if(total_length < 0.0) {
408 #ifdef VERBOSE
409         cerr << __FILE__ << ": Found a path of length " << total_length << endl;
410 #endif
411         // Invert all the edges along the best path
412         v = _sink;
413         while(v->pred_edge_toward_source) {
414           e = v->pred_edge_toward_source;
415           v = e->origin_vertex;
416           e->invert();
417           // This is the only place where we change the occupations of
418           // edges
419           e->occupied = 1 - e->occupied;
420         }
421       }
422     }
423
424   } while(total_length < 0.0);
425
426   // Put back the graph in its original state (i.e. invert edges which
427   // have been inverted in the process)
428   for(int k = 0; k < _nb_edges; k++) {
429     e = _edges + k;
430     if(e->occupied) { e->invert(); }
431   }
432 }
433
434 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
435   Edge *f, *next = 0;
436   int l = 0, nb_occupied_next;
437
438   if(path) {
439     path->nodes[l++] = e->origin_vertex - _vertices;
440     path->length = e->length;
441   } else l++;
442
443   while(e->terminal_vertex != _sink) {
444     if(path) {
445       path->nodes[l++] = e->terminal_vertex - _vertices;
446       path->length += e->length;
447     } else l++;
448
449     nb_occupied_next = 0;
450     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
451       if(f->occupied) { nb_occupied_next++; next = f; }
452     }
453
454 #ifdef DEBUG
455     if(nb_occupied_next == 0) {
456       cerr << __FILE__ << ": retrieve_one_path: Non-sink end point." << endl;
457       abort();
458     }
459
460     else if(nb_occupied_next > 1) {
461       cerr << __FILE__ << ": retrieve_one_path: Non node-disjoint paths." << endl;
462       abort();
463     }
464 #endif
465
466     e = next;
467   }
468
469   if(path) {
470     path->nodes[l++] = e->terminal_vertex - _vertices;
471     path->length += e->length;
472   } else l++;
473
474   return l;
475 }
476
477 void MTPGraph::retrieve_disjoint_paths() {
478   Edge *e;
479   int p, l;
480
481   for(int p = 0; p < nb_paths; p++) delete paths[p];
482   delete[] paths;
483
484   nb_paths = 0;
485   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
486     if(e->occupied) { nb_paths++; }
487   }
488
489   paths = new Path *[nb_paths];
490
491   p = 0;
492   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
493     if(e->occupied) {
494       l = retrieve_one_path(e, 0);
495       paths[p] = new Path(l);
496       retrieve_one_path(e, paths[p]);
497       p++;
498     }
499   }
500 }