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