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