12017c20a1b9039e1e62ebd5a96ed9ee0a90ac92
[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
50   int last_change; // Used to mark which edges have already been
51                    // processed in some methods
52
53   Vertex **heap_position;
54
55   Vertex();
56
57   inline void add_leaving_edge(Edge *e);
58   inline void del_leaving_edge(Edge *e);
59 };
60
61 //////////////////////////////////////////////////////////////////////
62
63 void Edge::invert() {
64   length = - length;
65   positivized_length = - positivized_length;
66   origin_vertex->del_leaving_edge(this);
67   terminal_vertex->add_leaving_edge(this);
68   Vertex *t = terminal_vertex;
69   terminal_vertex = origin_vertex;
70   origin_vertex = t;
71 }
72
73 //////////////////////////////////////////////////////////////////////
74
75 Vertex::Vertex() {
76   leaving_edges = 0;
77 }
78
79 void Vertex::add_leaving_edge(Edge *e) {
80   e->next_leaving_edge = leaving_edges;
81   e->pred_leaving_edge = 0;
82   if(leaving_edges) { leaving_edges->pred_leaving_edge = e; }
83   leaving_edges = e;
84 }
85
86 void Vertex::del_leaving_edge(Edge *e) {
87   if(e == leaving_edges) {
88     leaving_edges = e->next_leaving_edge;
89   }
90   if(e->pred_leaving_edge) {
91     e->pred_leaving_edge->next_leaving_edge = e->next_leaving_edge;
92   }
93   if(e->next_leaving_edge) {
94     e->next_leaving_edge->pred_leaving_edge = e->pred_leaving_edge;
95   }
96 }
97
98 //////////////////////////////////////////////////////////////////////
99
100 static int compare_vertex(const void *v1, const void *v2) {
101   return (*((Vertex **) v1))->last_change - (*((Vertex **) v2))->last_change;
102 }
103
104 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
105                    int *vertex_from, int *vertex_to,
106                    int source, int sink) {
107   _nb_vertices = nb_vertices;
108   _nb_edges = nb_edges;
109
110   _edges = new Edge[_nb_edges];
111   _vertices = new Vertex[_nb_vertices];
112   _heap = new Vertex *[_nb_vertices];
113   _dp_order = new Vertex *[_nb_vertices];
114
115   _source = &_vertices[source];
116   _sink = &_vertices[sink];
117
118   for(int e = 0; e < nb_edges; e++) {
119     _vertices[vertex_from[e]].add_leaving_edge(_edges + e);
120     _edges[e].occupied = 0;
121     _edges[e].origin_vertex = _vertices + vertex_from[e];
122     _edges[e].terminal_vertex = _vertices + vertex_to[e];
123   }
124
125   for(int v = 0; v < _nb_vertices; v++) {
126     _heap[v] = &_vertices[v];
127     _vertices[v].heap_position = &_heap[v];
128   }
129
130   paths = 0;
131   nb_paths = 0;
132
133   if(is_dag()) {
134     // Here the last_change field of every vertex tells us how many
135     // iterations of DP we need to reach it. Hence we only have to
136     // process the vertex in that order.
137     for(int v = 0; v < _nb_vertices; v++) { _dp_order[v] = &_vertices[v]; }
138     qsort(_dp_order, _nb_vertices, sizeof(Vertex *), compare_vertex);
139   } else {
140     cerr << __FILE__ << ": This graph is not a DAG." << endl;
141     abort();
142   }
143 }
144
145 MTPGraph::~MTPGraph() {
146   delete[] _vertices;
147   delete[] _dp_order;
148   delete[] _heap;
149   delete[] _edges;
150   for(int p = 0; p < nb_paths; p++) delete paths[p];
151   delete[] paths;
152 }
153
154 //////////////////////////////////////////////////////////////////////
155
156 void MTPGraph::print(ostream *os) {
157   for(int k = 0; k < _nb_edges; k++) {
158     Edge *e = _edges + k;
159     (*os) << e->origin_vertex - _vertices
160          << " -> "
161          << e->terminal_vertex - _vertices
162          << " "
163          << e->length;
164     if(e->occupied) {
165       (*os) << " *";
166     }
167     (*os) << endl;
168   }
169 }
170
171 void MTPGraph::print_dot(ostream *os) {
172   (*os) << "digraph {" << endl;
173   (*os) << "        rankdir=\"LR\";" << endl;
174   (*os) << "        node [shape=circle,width=0.75,fixedsize=true];" << endl;
175   (*os) << "        edge [color=gray,arrowhead=open]" << endl;
176   (*os) << "        " << _source - _vertices << " [peripheries=2];" << endl;
177   (*os) << "        " << _sink - _vertices << " [peripheries=2];" << endl;
178   for(int k = 0; k < _nb_edges; k++) {
179     Edge *e = _edges + k;
180     (*os) << "        "
181           << e->origin_vertex - _vertices
182           << " -> "
183           << e->terminal_vertex - _vertices
184           << " [";
185     if(e->occupied) {
186       (*os) << "style=bold,color=black,";
187     }
188     (*os) << "label=\"" << e->length << "\"];" << endl;
189   }
190   (*os) << "}" << endl;
191 }
192
193 //////////////////////////////////////////////////////////////////////
194
195 void MTPGraph::update_positivized_lengths() {
196   for(int k = 0; k < _nb_edges; k++) {
197     Edge *e = _edges + k;
198     e->positivized_length +=
199       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
200   }
201 }
202
203 void MTPGraph::force_positivized_lengths() {
204 #ifdef VERBOSE
205   scalar_t residual_error = 0.0;
206   scalar_t max_error = 0.0;
207 #endif
208   for(int k = 0; k < _nb_edges; k++) {
209     Edge *e = _edges + k;
210
211     if(e->positivized_length < 0) {
212
213 #ifdef VERBOSE
214       if((e->origin_vertex->last_change < 0 && e->terminal_vertex->last_change >= 0) ||
215          (e->origin_vertex->last_change >= 0 && e->terminal_vertex->last_change < 0)) {
216         cout << "Inconsistent non-connexity (this should never happen)." << endl;
217         abort();
218       }
219       if(e->origin_vertex->last_change >= 0 &&
220          e->terminal_vertex->last_change >= 0 &&
221          e->positivized_length < 0) {
222         residual_error -= e->positivized_length;
223         max_error = max(max_error, - e->positivized_length);
224       }
225 #endif
226       e->positivized_length = 0.0;
227     }
228   }
229 #ifdef VERBOSE
230   cerr << "residual_error " << residual_error << " max_error " << residual_error << endl;
231 #endif
232 }
233
234 int MTPGraph::is_dag() {
235   Vertex *v;
236   Edge *e;
237
238   Vertex **active = new Vertex *[_nb_vertices];
239
240   // We put everybody in the active
241   for(int k = 0; k < _nb_vertices; k++) {
242     _vertices[k].last_change = 0;
243     active[k] = &_vertices[k];
244   }
245
246   int iteration = 1;
247   int nb_active = _nb_vertices, pred_nb_active;
248
249   do {
250     // We set the last_change field of all the vertices with incoming
251     // edges to the current iteration 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->last_change = iteration;
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->last_change == iteration) {
266         active[nb_active++] = v;
267       }
268     }
269
270     iteration++;
271   } while(nb_active < pred_nb_active);
272
273   delete[] active;
274
275   return nb_active == 0;
276 }
277
278 #ifdef DEBUG
279 void print_heap(int first, int heap_size, Vertex **heap, int depth, Vertex *vertices) {
280   // if(depth == 0) cout << "** START_HEAP ********************************************************" << endl;
281   // if(first < heap_size) {
282     // print_heap((first + 1) * 2 - 1, heap_size, heap, depth + 1, vertices);
283     // for(int d = 0; d < depth; d++) cout << "  ";
284     // cout << "[" << heap[first] - vertices << "] ";
285     // if(heap[first]->distance_from_source == FLT_MAX) cout << "inf";
286     // else cout << heap[first]->distance_from_source;
287     // cout << endl;
288     // print_heap((first + 1) * 2, heap_size, heap, depth + 1, vertices);
289   // }
290   // if(depth == 0) cout << "** END_HEAP **********************************************************" << endl;
291 }
292
293 void check_heap(Vertex **heap, int heap_size, Vertex *vertices, int nb_vertices) {
294   Vertex **p, **h;
295   int *used = new int[nb_vertices];
296   for(int v = 0; v < nb_vertices; v++) used[v] = 0;
297   for(int k = 0; k < heap_size; k++) {
298     used[heap[k] - vertices]++;
299     h = heap + k;
300     if(h != (*h)->heap_position) abort();
301     if(k > 0) {
302       p = heap + (h - heap + 1) / 2 - 1;
303       if((*h)->distance_from_source < (*p)->distance_from_source) abort();
304     }
305   }
306   for(int v = 0; v < nb_vertices; v++) {
307     cout << used[v];
308     if(used[v] > 1) abort();
309   }
310   cout << endl;
311   delete[] used;
312 }
313 #endif
314
315 void MTPGraph::decrease_distance_in_heap(Vertex *v) {
316 #ifdef DEBUG
317   // cout << "START decrease_distance_in_heap" << endl;
318   // print_heap(0, _heap_size, _heap, 0, _vertices);
319 #endif
320   Vertex **p, **h;
321   // There is some beauty in that
322   h = v->heap_position;
323   while(h > _heap &&
324         (p = _heap + (h - _heap + 1) / 2 - 1,
325          (*p)->distance_from_source > (*h)->distance_from_source)) {
326 // #warning REMOVE
327     // cout << "SWAP [" << (*p) - _vertices << " | " << (*h) - _vertices << "]" << endl;
328     // if((*p) - _vertices == 6 && (*h) - _vertices == 96) abort();
329     swap(*p, *h);
330     swap((*p)->heap_position, (*h)->heap_position);
331     h = p;
332   }
333 #ifdef DEBUG
334   // check_heap(_heap, _heap_size, _vertices, _nb_vertices);
335   // print_heap(0, _heap_size, _heap, 0, _vertices);
336 #endif
337 }
338
339 void MTPGraph::increase_distance_in_heap(Vertex *v) {
340 #ifdef DEBUG
341   // cout << "START increase_distance_in_heap" << endl;
342   // print_heap(0, _heap_size, _heap, 0, _vertices);
343 #endif
344   Vertex **c1, **c2, **h;
345   // There is some beauty in that
346   h = v->heap_position;
347   while(c1 = _heap + 2 * (h - _heap + 1) - 1, c2 = c1 + 1,
348         (c1 < _heap + _heap_size &&
349          (*c1)->distance_from_source < (*h)->distance_from_source)
350         ||
351         (c2 < _heap + _heap_size &&
352           (*c2)->distance_from_source < (*h)->distance_from_source)
353         ) {
354     if(c1 < _heap + _heap_size &&
355        !(c2 < _heap + _heap_size &&
356          (*c2)->distance_from_source < (*c1)->distance_from_source)){
357       swap(*c1, *h);
358       swap((*c1)->heap_position, (*h)->heap_position);
359       h = c1;
360     } else {
361       swap(*c2, *h);
362       swap((*c2)->heap_position, (*h)->heap_position);
363       h = c2;
364     }
365   }
366 #ifdef DEBUG
367   // check_heap(_heap, _heap_size, _vertices, _nb_vertices);
368   // print_heap(0, _heap_size, _heap, 0, _vertices);
369 #endif
370 }
371
372 void MTPGraph::dp_distance_propagation() {
373   Vertex *v, *tv;
374   Edge *e;
375   scalar_t d;
376
377   for(int k = 0; k < _nb_vertices; k++) {
378     _vertices[k].distance_from_source = FLT_MAX;
379     _vertices[k].pred_edge_toward_source = 0;
380   }
381
382   _source->distance_from_source = 0;
383
384   for(int k = 0; k < _nb_vertices; k++) {
385     v = _dp_order[k];
386     for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
387       d = v->distance_from_source + e->positivized_length;
388       tv = e->terminal_vertex;
389       if(d < tv->distance_from_source) {
390         tv->distance_from_source = d;
391         tv->pred_edge_toward_source = e;
392         decrease_distance_in_heap(tv);
393       }
394     }
395   }
396
397 #ifdef DEBUG
398   for(int k = 0; k < _nb_vertices; k++) {
399     if(_vertices[k].distance_from_source == FLT_MAX) abort();
400   }
401 #endif
402 }
403
404 // This method does not change the edge occupation. It only set
405 // properly, for every vertex, the fields distance_from_source and
406 // pred_edge_toward_source.
407
408 void MTPGraph::find_shortest_path() {
409   Vertex *v, *tv;
410   Edge *e;
411   scalar_t d;
412
413 #ifdef DEBUG
414   if(is_dag()) {
415     cout << "find_shortest_path: DAG -> ok" << endl;
416   } else {
417     for(int e = 0; e < _nb_edges; e++) {
418       if(_edges[e].positivized_length < 0) abort();
419     }
420     cout << "find_shortest_path: All positivized_length are positive -> ok" << endl;
421   }
422 #endif
423
424   for(int k = 0; k < _nb_vertices; k++) {
425     _vertices[k].distance_from_source = FLT_MAX;
426     _vertices[k].pred_edge_toward_source = 0;
427   }
428
429   _heap_size = _nb_vertices;
430   _source->distance_from_source = 0;
431   decrease_distance_in_heap(_source);
432
433   do {
434 #ifdef DEBUG
435     for(int k = 0; k < _heap_size; k++) {
436       if(_heap[0]->distance_from_source > _heap[k]->distance_from_source) abort();
437     }
438     // cout << "OK!" << endl;
439 #endif
440
441     v = _heap[0];
442     _heap_size--;
443     Vertex **a = _heap, **b = _heap + _heap_size;
444     swap(*a, *b); swap((*a)->heap_position, (*b)->heap_position);
445     increase_distance_in_heap(_heap[0]);
446
447     for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
448       d = v->distance_from_source + e->positivized_length;
449       tv = e->terminal_vertex;
450       if(d < tv->distance_from_source) {
451         ASSERT(tv->heap_position - _heap < _heap_size);
452         tv->distance_from_source = d;
453         tv->pred_edge_toward_source = e;
454         decrease_distance_in_heap(tv);
455       }
456 #ifdef DEBUG
457       for(int k = 0; k < _heap_size; k++) {
458         if(_heap[0]->distance_from_source > _heap[k]->distance_from_source) abort();
459       }
460 #endif
461     }
462   } while(_heap_size > 0);
463
464 #ifdef DEBUG
465   for(int k = 0; k < _nb_vertices; k++) {
466     v = &_vertices[k];
467     for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
468       d = v->distance_from_source + e->positivized_length;
469       tv = e->terminal_vertex;
470       if(d < tv->distance_from_source) abort();
471     }
472   }
473 #endif
474   cout << "DONE!" << endl;
475 }
476
477 void MTPGraph::find_best_paths(scalar_t *lengths) {
478   scalar_t total_length;
479   Vertex *v;
480   Edge *e;
481
482   for(int e = 0; e < _nb_edges; e++) {
483     _edges[e].length = lengths[e];
484     _edges[e].occupied = 0;
485     _edges[e].positivized_length = _edges[e].length;
486   }
487
488   // // We call find_shortest_path here to set properly the distances to
489   // // the source, so that we can make all the edge lengths positive at
490   // // the first iteration.
491   // find_shortest_path();
492
493   dp_distance_propagation();
494
495   do {
496     update_positivized_lengths();
497     force_positivized_lengths();
498     find_shortest_path();
499
500     total_length = 0.0;
501
502     // Do we reach the sink?
503     if(_sink->pred_edge_toward_source) {
504       // If yes, compute the length of the best path according to the
505       // original edge lengths
506       v = _sink;
507       while(v->pred_edge_toward_source) {
508         total_length += v->pred_edge_toward_source->length;
509         v = v->pred_edge_toward_source->origin_vertex;
510       }
511       // If that length is negative
512       if(total_length < 0.0) {
513 #ifdef VERBOSE
514         cerr << "Found a path of length " << total_length << endl;
515 #endif
516         // Invert all the edges along the best path
517         v = _sink;
518         while(v->pred_edge_toward_source) {
519           e = v->pred_edge_toward_source;
520           v = e->origin_vertex;
521           e->invert();
522           // This is the only place where we change the occupations of
523           // edges
524           e->occupied = 1 - e->occupied;
525         }
526       }
527     }
528
529   } while(total_length < 0.0);
530
531   // Put back the graph in its original state (i.e. invert edges which
532   // have been inverted in the process)
533   for(int k = 0; k < _nb_edges; k++) {
534     e = _edges + k;
535     if(e->occupied) { e->invert(); }
536   }
537 }
538
539 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
540   Edge *f, *next = 0;
541   int l = 0, nb_occupied_next;
542
543   if(path) {
544     path->nodes[l++] = e->origin_vertex - _vertices;
545     path->length = e->length;
546   } else l++;
547
548   while(e->terminal_vertex != _sink) {
549     if(path) {
550       path->nodes[l++] = e->terminal_vertex - _vertices;
551       path->length += e->length;
552     } else l++;
553
554     nb_occupied_next = 0;
555     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
556       if(f->occupied) { nb_occupied_next++; next = f; }
557     }
558
559 #ifdef DEBUG
560     if(nb_occupied_next == 0) {
561       cerr << "retrieve_one_path: Non-sink end point." << endl;
562       abort();
563     }
564
565     else if(nb_occupied_next > 1) {
566       cerr << "retrieve_one_path: Non node-disjoint paths." << endl;
567       abort();
568     }
569 #endif
570
571     e = next;
572   }
573
574   if(path) {
575     path->nodes[l++] = e->terminal_vertex - _vertices;
576     path->length += e->length;
577   } else l++;
578
579   return l;
580 }
581
582 void MTPGraph::retrieve_disjoint_paths() {
583   Edge *e;
584   int p, l;
585
586   for(int p = 0; p < nb_paths; p++) delete paths[p];
587   delete[] paths;
588
589   nb_paths = 0;
590   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
591     if(e->occupied) { nb_paths++; }
592   }
593
594   paths = new Path *[nb_paths];
595
596   p = 0;
597   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
598     if(e->occupied) {
599       l = retrieve_one_path(e, 0);
600       paths[p] = new Path(l);
601       retrieve_one_path(e, paths[p]);
602       p++;
603     }
604   }
605 }