Cosmetics (in particular allowed_motion -> allowed_motions).
[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 n = 0; n < _nb_vertices; n++) {
193     for(Edge *e = _vertices[n].leaving_edges; e; e = e->next_leaving_edge) {
194       if(e->positivized_length < 0) {
195 #ifdef VERBOSE
196         residual_error -= e->positivized_length;
197         max_error = max(max_error, - e->positivized_length);
198 #endif
199         e->positivized_length = 0.0;
200       }
201     }
202   }
203 #ifdef VERBOSE
204   cerr << "residual_error " << residual_error << " max_error " << residual_error << endl;
205 #endif
206 }
207
208 int MTPGraph::is_dag() {
209   Vertex *v;
210   Edge *e;
211
212   // We put everybody in the front
213   for(int k = 0; k < _nb_vertices; k++) {
214     _vertices[k].last_change = -1;
215     _front[k] = &_vertices[k];
216   }
217
218   int iteration = 0;
219   int front_size = _nb_vertices, pred_front_size;
220
221   do {
222     // We set the iteration field of all vertex with incoming edges to
223     // the current iteration value
224     for(int f = 0; f < front_size; f++) {
225       v = _front[f];
226       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
227         e->terminal_vertex->last_change = iteration;
228       }
229     }
230
231     pred_front_size = front_size;
232     front_size = 0;
233
234     // We remove all the vertices without incoming edge
235     for(int f = 0; f < pred_front_size; f++) {
236       v = _front[f];
237       if(v->last_change == iteration) {
238         _front[front_size++] = v;
239       }
240     }
241
242     iteration++;
243   } while(front_size < pred_front_size);
244
245   return front_size == 0;
246 }
247
248 // This method does not change the edge occupation. It only set
249 // properly for every vertex the fields distance_from_source and
250 // pred_edge_toward_source.
251
252 void MTPGraph::find_shortest_path() {
253   Vertex **tmp_front;
254   Vertex *v, *tv;
255   Edge *e;
256   scalar_t d;
257
258 #ifdef DEBUG
259   if(is_dag()) {
260     cout << "find_shortest_path: DAG -> ok" << endl;
261   } else {
262     for(int e = 0; e < _nb_edges; e++) {
263       if(_edges[e].positivized_length < 0)  abort();
264     }
265     cout << "find_shortest_path: All positivized_length are positive -> ok" << endl;
266   }
267 #endif
268
269   for(int k = 0; k < _nb_vertices; k++) {
270     _vertices[k].distance_from_source = FLT_MAX;
271     _vertices[k].pred_edge_toward_source = 0;
272     _vertices[k].last_change = -1;
273   }
274
275   int iteration = 0;
276
277   int front_size = 0, new_front_size;
278   _front[front_size++] = _source;
279   _source->distance_from_source = 0;
280
281   do {
282     new_front_size = 0;
283
284     for(int f = 0; f < front_size; f++) {
285       v = _front[f];
286       for(e = v->leaving_edges; e; e = e->next_leaving_edge) {
287         d = v->distance_from_source + e->positivized_length;
288         tv = e->terminal_vertex;
289         if(d < tv->distance_from_source) {
290           tv->distance_from_source = d;
291           tv->pred_edge_toward_source = e;
292           if(tv->last_change < iteration) {
293             _new_front[new_front_size++] = tv;
294             tv->last_change = iteration;
295           }
296         }
297       }
298     }
299
300     tmp_front = _new_front; _new_front = _front; _front = tmp_front;
301
302     front_size = new_front_size;
303
304     iteration++;
305   } while(front_size > 0);
306 }
307
308 void MTPGraph::find_best_paths(scalar_t *lengths) {
309   scalar_t total_length;
310   Vertex *v;
311   Edge *e;
312
313   for(int e = 0; e < _nb_edges; e++) {
314     _edges[e].length = lengths[e];
315     _edges[e].occupied = 0;
316     _edges[e].positivized_length = _edges[e].length;
317   }
318
319   // We call find_shortest_path here to set properly the distances to
320   // the source, so that we can make all the edge lengths positive at
321   // the first iteration.
322   find_shortest_path();
323
324   do {
325     update_positivized_lengths();
326     force_positivized_lengths();
327     find_shortest_path();
328
329     total_length = 0.0;
330
331     // Do we reach the sink?
332     if(_sink->pred_edge_toward_source) {
333       // If yes, compute the length of the best path according to the
334       // original edge lengths
335       v = _sink;
336       while(v->pred_edge_toward_source) {
337         total_length += v->pred_edge_toward_source->length;
338         v = v->pred_edge_toward_source->origin_vertex;
339       }
340       // If that length is negative
341       if(total_length < 0.0) {
342 #ifdef VERBOSE
343         cerr << "Found a path of length " << total_length << endl;
344 #endif
345         // Invert all the edges along the best path
346         v = _sink;
347         while(v->pred_edge_toward_source) {
348           e = v->pred_edge_toward_source;
349           v = e->origin_vertex;
350           e->invert();
351           // This is the only place where we change the occupations of
352           // edges
353           e->occupied = 1 - e->occupied;
354         }
355       }
356     }
357
358   } while(total_length < 0.0);
359
360   // Put back the graph in its original state (i.e. invert edges which
361   // have been inverted in the process)
362   for(int k = 0; k < _nb_edges; k++) {
363     Edge *e = _edges + k;
364     if(e->occupied) { e->invert(); }
365   }
366 }
367
368 int MTPGraph::retrieve_one_path(Edge *e, Path *path) {
369   Edge *f, *next = 0;
370   int l = 0;
371
372   if(path) {
373     path->nodes[l++] = e->origin_vertex->id;
374     path->length = e->length;
375   } else l++;
376
377   while(e->terminal_vertex != _sink) {
378     if(path) {
379       path->nodes[l++] = e->terminal_vertex->id;
380       path->length += e->length;
381     } else l++;
382     int nb_choices = 0;
383     for(f = e->terminal_vertex->leaving_edges; f; f = f->next_leaving_edge) {
384       if(f->occupied) { nb_choices++; next = f; }
385       if(nb_choices == 0) {
386         cerr << "retrieve_one_path: Non-sink end point." << endl;
387         abort();
388       }
389       if(nb_choices > 1) {
390         cerr << "retrieve_one_path: Non node-disjoint paths." << endl;
391         abort();
392       }
393     }
394     e = next;
395   }
396
397   if(path) {
398     path->nodes[l++] = e->terminal_vertex->id;
399     path->length += e->length;
400   } else l++;
401
402   return l;
403 }
404
405 void MTPGraph::retrieve_disjoint_paths() {
406   Edge *e;
407
408   for(int p = 0; p < nb_paths; p++) delete paths[p];
409   delete[] paths;
410
411   nb_paths = 0;
412   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
413     if(e->occupied) { nb_paths++; }
414   }
415
416   paths = new Path *[nb_paths];
417
418   int p = 0;
419   for(e = _source->leaving_edges; e; e = e->next_leaving_edge) {
420     if(e->occupied) {
421       int l = retrieve_one_path(e, 0);
422       paths[p] = new Path(l);
423       retrieve_one_path(e, paths[p]);
424       p++;
425     }
426   }
427 }