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