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