5371732a03e9c85e3b357f16464e36773535a0b7
[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();
54
55   inline void add_leaving_edge(Edge *e);
56   inline void del_leaving_edge(Edge *e);
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 //////////////////////////////////////////////////////////////////////
97
98 MTPGraph::MTPGraph(int nb_vertices, int nb_edges,
99                    int *vertex_from, int *vertex_to,
100                    int source, int sink) {
101   _nb_vertices = nb_vertices;
102   _nb_edges = nb_edges;
103
104   _edges = new Edge[_nb_edges];
105   _vertices = new Vertex[_nb_vertices];
106   _front = new Vertex *[_nb_vertices];
107   _new_front = new Vertex *[_nb_vertices];
108
109   _source = &_vertices[source];
110   _sink = &_vertices[sink];
111
112   for(int e = 0; e < nb_edges; e++) {
113     _vertices[vertex_from[e]].add_leaving_edge(_edges + e);
114     _edges[e].occupied = 0;
115     _edges[e].origin_vertex = _vertices + vertex_from[e];
116     _edges[e].terminal_vertex = _vertices + vertex_to[e];
117   }
118
119   paths = 0;
120   nb_paths = 0;
121 }
122
123 MTPGraph::~MTPGraph() {
124   delete[] _vertices;
125   delete[] _edges;
126   delete[] _front;
127   delete[] _new_front;
128   for(int p = 0; p < nb_paths; p++) delete paths[p];
129   delete[] paths;
130 }
131
132 //////////////////////////////////////////////////////////////////////
133
134 void MTPGraph::print(ostream *os) {
135   for(int k = 0; k < _nb_edges; k++) {
136     Edge *e = _edges + k;
137     (*os) << e->origin_vertex - _vertices
138          << " -> "
139          << e->terminal_vertex - _vertices
140          << " "
141          << e->length;
142     if(e->occupied) {
143       (*os) << " *";
144     }
145     (*os) << endl;
146   }
147 }
148
149 void MTPGraph::print_dot(ostream *os) {
150   (*os) << "digraph {" << endl;
151   (*os) << "        rankdir=\"LR\";" << endl;
152   (*os) << "        node [shape=circle,width=0.75,fixedsize=true];" << endl;
153   (*os) << "        edge [color=gray,arrowhead=open]" << endl;
154   (*os) << "        " << _source - _vertices << " [peripheries=2];" << endl;
155   (*os) << "        " << _sink - _vertices << " [peripheries=2];" << endl;
156   for(int k = 0; k < _nb_edges; k++) {
157     Edge *e = _edges + k;
158     (*os) << "        "
159           << e->origin_vertex - _vertices
160           << " -> "
161           << e->terminal_vertex - _vertices
162           << " [";
163     if(e->occupied) {
164       (*os) << "style=bold,color=black,";
165     }
166     (*os) << "label=\"" << e->length << "\"];" << endl;
167   }
168   (*os) << "}" << endl;
169 }
170
171 //////////////////////////////////////////////////////////////////////
172
173 void MTPGraph::update_positivized_lengths() {
174   for(int k = 0; k < _nb_edges; k++) {
175     Edge *e = _edges + k;
176     e->positivized_length +=
177       e->origin_vertex->distance_from_source - e->terminal_vertex->distance_from_source;
178   }
179 }
180
181 void MTPGraph::force_positivized_lengths() {
182 #ifdef VERBOSE
183   scalar_t residual_error = 0.0;
184   scalar_t max_error = 0.0;
185 #endif
186   for(int k = 0; k < _nb_edges; k++) {
187     Edge *e = _edges + k;
188
189     if(e->positivized_length < 0) {
190
191 #ifdef VERBOSE
192       if((e->origin_vertex->last_change < 0 && e->terminal_vertex->last_change >= 0) ||
193          (e->origin_vertex->last_change >= 0 && e->terminal_vertex->last_change < 0)) {
194         cout << "Inconsistent non-connexity (this should never happen)." << endl;
195         abort();
196       }
197       if(e->origin_vertex->last_change >= 0 &&
198          e->terminal_vertex->last_change >= 0 &&
199          e->positivized_length < 0) {
200         residual_error -= e->positivized_length;
201         max_error = max(max_error, - e->positivized_length);
202       }
203 #endif
204       e->positivized_length = 0.0;
205     }
206   }
207 #ifdef VERBOSE
208   cerr << "residual_error " << residual_error << " max_error " << residual_error << endl;
209 #endif
210 }
211
212 int MTPGraph::is_dag() {
213   Vertex *v;
214   Edge *e;
215
216   // We put everybody in the front
217   for(int k = 0; k < _nb_vertices; k++) {
218     _vertices[k].last_change = -1;
219     _front[k] = &_vertices[k];
220   }
221
222   int iteration = 0;
223   int front_size = _nb_vertices, pred_front_size;
224
225   do {
226     // We set the last_change field of all the vertices with incoming
227     // edges to the current iteration value
228     for(int f = 0; f < front_size; f++) {
229       v = _front[f];
230       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
231         e->terminal_vertex->last_change = iteration;
232       }
233     }
234
235     pred_front_size = front_size;
236     front_size = 0;
237
238     // We keep all the vertices with incoming nodes
239     for(int f = 0; f < pred_front_size; f++) {
240       v = _front[f];
241       if(v->last_change == iteration) {
242         _front[front_size++] = v;
243       }
244     }
245
246     iteration++;
247   } while(front_size < pred_front_size);
248
249   return front_size == 0;
250 }
251
252 // This method does not change the edge occupation. It only set
253 // properly, for every vertex, the fields distance_from_source and
254 // pred_edge_toward_source.
255
256 void MTPGraph::find_shortest_path() {
257   Vertex **tmp_front;
258   Vertex *v, *tv;
259   Edge *e;
260   scalar_t d;
261
262 #ifdef DEBUG
263   if(is_dag()) {
264     cout << "find_shortest_path: DAG -> ok" << endl;
265   } else {
266     for(int e = 0; e < _nb_edges; e++) {
267       if(_edges[e].positivized_length < 0)  abort();
268     }
269     cout << "find_shortest_path: All positivized_length are positive -> ok" << endl;
270   }
271 #endif
272
273   for(int k = 0; k < _nb_vertices; k++) {
274     _vertices[k].distance_from_source = FLT_MAX;
275     _vertices[k].pred_edge_toward_source = 0;
276     _vertices[k].last_change = -1;
277   }
278
279   int iteration = 0;
280
281   int front_size = 0, new_front_size;
282   _front[front_size++] = _source;
283   _source->distance_from_source = 0;
284
285   do {
286     new_front_size = 0;
287
288     for(int f = 0; f < front_size; f++) {
289       v = _front[f];
290       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
291         d = v->distance_from_source + e->positivized_length;
292         tv = e->terminal_vertex;
293         if(d < tv->distance_from_source) {
294           tv->distance_from_source = d;
295           tv->pred_edge_toward_source = e;
296           if(tv->last_change < iteration) {
297             _new_front[new_front_size++] = tv;
298             tv->last_change = iteration;
299           }
300         }
301       }
302     }
303
304     tmp_front = _new_front; _new_front = _front; _front = tmp_front;
305
306     front_size = new_front_size;
307
308     iteration++;
309   } while(front_size > 0);
310 }
311
312 void MTPGraph::find_best_paths(scalar_t *lengths) {
313   scalar_t total_length;
314   Vertex *v;
315   Edge *e;
316
317   for(int e = 0; e < _nb_edges; e++) {
318     _edges[e].length = lengths[e];
319     _edges[e].occupied = 0;
320     _edges[e].positivized_length = _edges[e].length;
321   }
322
323   // We call find_shortest_path here to set properly the distances to
324   // the source, so that we can make all the edge lengths positive at
325   // the first iteration.
326   find_shortest_path();
327
328   do {
329     update_positivized_lengths();
330     force_positivized_lengths();
331     find_shortest_path();
332
333     total_length = 0.0;
334
335     // Do we reach the sink?
336     if(_sink->pred_edge_toward_source) {
337       // If yes, compute the length of the best path according to the
338       // original edge lengths
339       v = _sink;
340       while(v->pred_edge_toward_source) {
341         total_length += v->pred_edge_toward_source->length;
342         v = v->pred_edge_toward_source->origin_vertex;
343       }
344       // If that length is negative
345       if(total_length < 0.0) {
346 #ifdef VERBOSE
347         cerr << "Found a path of length " << total_length << endl;
348 #endif
349         // Invert all the edges along the best path
350         v = _sink;
351         while(v->pred_edge_toward_source) {
352           e = v->pred_edge_toward_source;
353           v = e->origin_vertex;
354           e->invert();
355           // This is the only place where we change the occupations of
356           // edges
357           e->occupied = 1 - e->occupied;
358         }
359       }
360     }
361
362   } while(total_length < 0.0);
363
364   // Put back the graph in its original state (i.e. invert edges which
365   // have been inverted in the process)
366   for(int k = 0; k < _nb_edges; k++) {
367     e = _edges + k;
368     if(e->occupied) { e->invert(); }
369   }
370 }
371
372 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
373   Edge *f, *next = 0;
374   int l = 0, nb_occupied_next;
375
376   if(path) {
377     path->nodes[l++] = e->origin_vertex - _vertices;
378     path->length = e->length;
379   } else l++;
380
381   while(e->terminal_vertex != _sink) {
382     if(path) {
383       path->nodes[l++] = e->terminal_vertex - _vertices;
384       path->length += e->length;
385     } else l++;
386
387     nb_occupied_next = 0;
388     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
389       if(f->occupied) { nb_occupied_next++; next = f; }
390     }
391
392 #ifdef DEBUG
393     if(nb_occupied_next == 0) {
394       cerr << "retrieve_one_path: Non-sink end point." << endl;
395       abort();
396     }
397
398     else if(nb_occupied_next > 1) {
399       cerr << "retrieve_one_path: Non node-disjoint paths." << endl;
400       abort();
401     }
402 #endif
403
404     e = next;
405   }
406
407   if(path) {
408     path->nodes[l++] = e->terminal_vertex - _vertices;
409     path->length += e->length;
410   } else l++;
411
412   return l;
413 }
414
415 void MTPGraph::retrieve_disjoint_paths() {
416   Edge *e;
417   int p, l;
418
419   for(int p = 0; p < nb_paths; p++) delete paths[p];
420   delete[] paths;
421
422   nb_paths = 0;
423   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
424     if(e->occupied) { nb_paths++; }
425   }
426
427   paths = new Path *[nb_paths];
428
429   p = 0;
430   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
431     if(e->occupied) {
432       l = retrieve_one_path(e, 0);
433       paths[p] = new Path(l);
434       retrieve_one_path(e, paths[p]);
435       p++;
436     }
437   }
438 }